以下代码编译并执行时没有任何错误或警告。但给出了意想不到的结果。
代码:
import java.util.LinkedList;
import java.util.Scanner;
//defining a custom data-type (class)
class LLObj{
static int NodeInt;
static char NodeChar;
LLObj(int x, char y){
NodeInt = x;
NodeChar = y;
}
}
class LLexp{
static LinkedList<LLObj> list = new LinkedList<>();
public static void main(String[] args){
list.addLast(new LLObj(5,'c'));
System.out.println(list.get(0).NodeInt);
System.out.println(list.get(0).NodeChar);
list.addLast(new LLObj(7,'h'));
System.out.println(list.get(0).NodeInt);
System.out.println(list.get(0).NodeChar);
System.out.println(list.get(1).NodeInt);
System.out.println(list.get(1).NodeChar);
}
}
预期输出 -
5
c
5
c
7
h
获得的输出 -
5
c
7
h
7
h
- 为什么会发生这种情况?
- 如何获得预期结果?
最佳答案
这就是问题:
static int NodeInt;
static char NodeChar;
如果目的是让每个 LLObj
都有自己的值(这似乎是可能的),那么这些应该是实例变量。
理解实例字段/方法和静态字段/方法之间的区别非常重要。请参阅Java tutorial了解更多详情。
关于java - java中链表代码出现意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15655745/