【问题标题】:How to add to ArrayList in a For loop如何在 For 循环中添加到 ArrayList
【发布时间】:2016-01-18 08:01:30
【问题描述】:

我有一个随机生成的信息序列。我想将该信息保存在某种变量中,以便可以在其他地方调用它。我认为我想使用一个 ArrayList,但我不确定如何在 for 循环中添加信息(这是创建它的地方)。我的代码如下:

public static ArrayList<String> phoneList

public static void main(String[] args){

    Random randomNumber = new Random();
    int howMany = randomNumber.nextInt(11);;
    String holding; 

    for (int i=0; i < howMany; i++){
        int itemRandNum = randomNumber.nextInt(11);//for all Item Categories
        int priceRandNum = randomNumber.nextInt(11);//Prices for all categories
        holding = phones[itemRandNum]+" $"+ priceOfPhones[priceRandNum]; 

        //System.out.println(holding);
        phoneList.add("holding"); //here is where I would like to add the information 
                                //contained in "holding" to the "phoneList" ArrayList.

    }

    System.out.println(phoneList);
}

我收到 NullPointerException。如果在这里使用 ArrayList 不是最好的,那会是什么?

感谢您提供的任何帮助。

【问题讨论】:

  • 首先你错过了第一行的分号。您可以根据要求使用 arrayList 或任何适当的数据结构。要使用 arraylist,您需要先初始化它。 PhoneList = new ArrayList();我在任何地方都没有看到声明的电话数组,也许它是引发 NullPointerException 的电话

标签: java android for-loop arraylist


【解决方案1】:

public static void String Main(String[] args) 表示这与 Android 没有太大关系。

首先,实例化列表(在for 循环之外):

phoneList = new ArrayList<>(howMany); //Adding "howMany" is optional. It just sets the List's initial size.

然后,添加值:

for (int i = 0; i < howMany; i++) {
    //...
    phoneList.add(holding); 
    //Don't place holding in quotation marks, else you'll just add "holding" for every entry!
}

【讨论】:

  • 我没有在顶部包含所有初始化程序(有很多),但我正在初始化它。但是,我只是将它初始化为“public static ArrayList phoneList;”,这是错误的。我选择您的作为“答案”,因为您还帮助解决了我错误放置的“”。谢谢你。此外,它是我正在构建的一个更大的 Android 应用程序的一小部分,因此是 android 标签。由于实际问题与 Android 几乎没有关系,我可能不应该使用该标签。 ://
【解决方案2】:

你得到一个NullPointerException 因为ArrayList phoneList 是空的,因为你没有初始化它。所以写

public static ArrayList<String> phoneList = new ArrayList<>();

【讨论】:

    【解决方案3】:

    实际上,您只是在声明类 ArrayList 而不是实例化它。任何时候你都需要使用一个类来创建同一个类的实例,这很简单,只需执行以下操作: public static ArrayList phoneList = new ArrayList()(如果你运行的是旧版本的 java),否则使用 public static ArrayList phoneList = new ArrayList()。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多