ArrayList写入自身问题

3

你好,我这里有一些简化的代码展示了我的问题。基本上,我似乎无法将内容添加到ArrayList的末尾,而是会覆盖原有内容。请帮忙解决。

Main

public class Main {

public static void main(String[] args) {
    HolderOfList h = new HolderOfList();
    h.addToHolder(new Num(2, "Bob"));
    h.addToHolder(new Num(3, "Cat"));
    h.addToHolder(new Num(4, "Dog"));
    h.printAll();
}
}

保存ArrayList的类

import java.util.ArrayList;
import java.util.List;

public class HolderOfList {
List<Num> num;

public HolderOfList() {
    num = new ArrayList<Num>();
}

void addToHolder(Num n) {
    num.add(n);
}

void printAll() {
    for (int i = 0; i < num.size(); i++) {
        System.out.println(num.get(i).getI() + num.get(i).getStr());
    }
}
}

在ArrayList中存储的元素

public class Num {

private static String str;
private static int i;

public Num(int i, String str) {
    this.str = str;
    this.i = i;
}

String getStr() {
    return str;
}

int getI() {
    return i;
}

}

期望的输出结果是

2Bob
3Cat
4Dog

但我得到的却是

4Dog
4Dog
4Dog

我有一个更大规模的项目也存在这个问题,有什么想法吗?

谢谢您提前的帮助。

1个回答

5

将您的Num变量中的static修饰符去掉,因为它们使得所有Num实例有效地共享同一个变量(虽然它们实际上是类的变量,但行为相同)。改成instance(非静态)变量。

换句话说,将以下内容更改:

public class Num {
  private static String str;
  private static int i;

转换为:

public class Num {
  private String str;
  private int i;

教训:要谨慎使用static修饰符,并且只有在有意义的情况下才使用。这里没有意义。

1
@user1724416:不用谢。教训是:要谨慎使用静态修饰符,只有在有意义的情况下才使用它。这里没有意义。 - Hovercraft Full Of Eels

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接