【问题标题】:Passing an Int and String argument to an arrayList index and String element将 Int 和 String 参数传递给 arrayList 索引和 String 元素
【发布时间】:2018-07-31 23:15:35
【问题描述】:
import java.util.ArrayList;

public class DataBase {
    public ArrayList<String> nameList = new ArrayList<>();
    public void nameAdd(String s, int i) {
        if (i < nameList.size()){
            nameList.add(i, s);
            //string not adding to arrayList, ive probably done it wrong.
        }
        System.out.println(s);
        System.out.println("nameList.size = " + nameList.size());
        System.out.println("arrayList number = " + i);
    }
}

我已经编写了大约一个月的代码,所以请原谅我的菜鸟,但我基本上是在尝试从我构建的 GUI 中获取一个字符串,将其剪切以获得一个名称,然后将该名称添加到“数据库”,当用户单击另一个按钮将其添加到其中时。我已经能够增加应该为arrayList中的字符串设置索引的i,但是arrayList的大小并没有增加,我得到了一大堆错误,因此我添加了if语句来阻止它尝试添加到尚未在 arrayList 中的索引。

【问题讨论】:

    标签: string arraylist indexing


    【解决方案1】:

    在您的代码中,我看到您的数组 nameList 始终为空。

    因为你有这一行:

    public ArrayList<String> nameList = new ArrayList<>();
    

    此时您创建了您的数组(空),但如果您第一次通过,则在您的 nameAdd 方法中:

    nameAdd('ADDFIRSTELEMENT', 0)
    

    您的if 状态始终为false

    if (i < nameList.size()){
        nameList.add(i, s);
        //string not adding to arrayList, ive probably done it wrong.
    }
    

    您必须按如下方式更改支票:

    if (i <= nameList.size())
    

    因为如果你的索引与大小相同,你可以在数组中添加你的元素。

    如果您愿意,可以使用 nameList ArrayList 对象的 contains 方法,以便查看您的字符串是否存在于数组中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-20
      • 2015-06-07
      • 2018-10-02
      • 2021-01-20
      • 2014-02-11
      • 2014-04-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多