2

您好我正在尝试将对象添加到 Arraylist 中,我正在使用 Java。但它没有按我的预期工作。

假设我们有一个 class Sentence,所以代码看起来像

ArrayList<Sentence> result = new ArrayList<Sentence>();
for (int i =0; i<10;i++)
{
    Sentence s = new Sentence(i.toString(),i);
    //there is a string and an int in this Sentence object need to be set
    result.add(s); 
}

以上工作正常。但我希望加快我的代码,所以我尝试只新建一个对象,代码变为:

ArrayList<Sentence> result = new ArrayList<Sentence>();
Sentence s = new Sentence(" ",0);
for (int i =0; i<10;i++)
{
    s.setString(i.toString());
    s.setInt(i);
    result.add(s); 
}

但是,在这种情况下,我的结果将变为空。我想我确实更改了对象中的内容s,但我不知道为什么它在result.add(s).

非常感谢您的回复。

4

4 回答 4

5

你的s变量总是指同一个对象。看起来您正在添加相同的对象 10 次,到 for 循环结束时,其字符串等于"9"且 int 等于9

于 2012-04-24T05:04:17.380 回答
3

在第二种情况下,您将 10 个指向单个Sentence实例的指针添加到ArrayList.

您必须制作 10Sentence才能将 10 指针插入ArrayList.

我认为您正在搞乱 Java 中的按值传递和按引用传递,为了澄清这一点,请查看这篇文章

这篇文章也可能对您有所帮助。

于 2012-04-24T05:04:31.330 回答
0
ArrayList<Sentence> result = new ArrayList<Sentence>();
for (int i =0; i<10;i++)
{
    result.add(new Sentence(i.toString(),i)); 
}

如果您想创建比使用此示例更少的代码行,但它不一定更优化。

于 2012-04-24T05:28:55.637 回答
0

为了防止重复对象。始终在使用前实例化它们。这样,您的 List 将有 n 个唯一对象,

于 2014-01-11T23:29:17.260 回答