【问题标题】:User input Arraylist用户输入 Arraylist
【发布时间】:2012-12-27 20:34:35
【问题描述】:

我想知道是否可以将对象存储到用户想要的数组列表中。对于我的程序,它通过“帐号”将用户数据存储到他们选择的单元格中,但是每次我输入新帐号时,它都会说数组基本上不够大。这是我的代码。如果有人可以提供帮助,将不胜感激。

ArrayList <Account> account = new ArrayList<Account>();
int accountNumber;
String nCity;
String nState;
String nZipCode;
String nLastName;
String nAddress;
String firstName;
String nAccount;

public void newAccount()
{
    Account a = new Account();
    a.firstName = JOptionPane.showInputDialog("What's your first name?");
    a.nLastName = JOptionPane.showInputDialog("What's your last name?");
    a.nAddress = JOptionPane.showInputDialog("What's your current address?");
    a.nCity= JOptionPane.showInputDialog("What's your current city?");
    a.nState = JOptionPane.showInputDialog("What's your current State?");
    a.nZipCode = JOptionPane.showInputDialog("What's your current Zip Code?");
    String num = JOptionPane.showInputDialog("What do you want your account number to be?");
    accountNumber = Integer.parseInt(num);
    account.add(accountNumber, a);

【问题讨论】:

  • 在添加或使用Map 结构之前使列表足够大。
  • @jlordo 如何让它足够大,我似乎无法找到在哪里放置数组列表应该有多大的值?
  • @Lightning.. 你确定你能编译那个代码吗?就目前而言,您的代码甚至无法编译。你是如何运行它的?
  • @RohitJain 它为我编译并运行,但随后它说“java.lang.IndexOutOfBoundsException:索引:1,大小:0(在 java.util.ArrayList 中)。我需要初始大小数量庞大,因此可以在创建新帐户时添加它们。
  • @Lightning while (list.size() &lt; needed_size) list.add(null);Map 会更适合您的用例。

标签: java arraylist bluej


【解决方案1】:

使用HashMap 并使用帐号作为密钥

    Map<Integer,Account> account =new Hashmap<Integer,Account>();
    account.put(accountNumber,a);

【讨论】:

    【解决方案2】:

    您已经创建了一个ArrayList&lt;Account&gt;,并以key-value 对的形式向其中添加元素。

    如果你想这样添加,你可能需要一个HashMap:-

    Map<Integer, Account> accounts = new HashMap<Integer, Account>();
    

    然后,要在其中添加条目,您可以使用Map#put() 方法:-

    accounts.put(accountNumber, a);
    

    【讨论】:

      【解决方案3】:

      同意以上关于使用地图的建议。

      您的“数组不够大”仅仅是因为您在尚未初始化索引时尝试指定 List 的索引。

      简单来说,你使用的是List这个方法:

      add(int index, E 元素) 在此列表中的指定位置插入指定元素。

      关键字是插入。 因此,想象一下,如果您的“accountNumber”是 100,而您之前没有 99 个元素,那么尝试插入在逻辑上将毫无意义,因为您将插入到任何地方。

      JavaSE6 API 在这个方法下说:

      IndexOutOfBoundsException - 如果索引超出范围 (index size())

      顺便说一句,如果您可以使用另一个解决方案,除了使用 Map 之外,还可以将 accountNumber 作为 Account 的另一个字段,您现在可以将 List 与单参数 add() 方法一起使用。

      【讨论】:

        猜你喜欢
        • 2014-03-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多