以下是链接列表的简单实现。我刚刚添加了相关代码。 首先,我在列表中添加一些值,10,990和10000.当我搜索相同的值时,我得到key = 10,但是对于key = 990和key = 10000则为false,尽管它应该是真的。此外,如果我将第二个值从990更改为99并搜索key = 99,这次我得到一个真实的。
我不确定使用泛型类型。我想我在那里做错了什么。因为如果我用int替换泛型类型,我会得到正确的行为。请建议。
public class LinkedListTest {
public static void main(String[] args) {
LinkedList<Integer> num = new LinkedList<Integer>();
num.add(10);
num.add(990);
num.add(10000);
int key = 10;
System.out.println("Key " + key + " found ?" + num.findValue(key));
key = 990; //also checked for Integer key = 990
System.out.println("Key " + key + " found ?" + num.findValue(key));
key = 10000;
System.out.println("Key " + key + " found ?" + num.findValue(key));
}
}
class LinkedList<T>{
private Node<T> first;
private class Node<T>{
private T data;
private Node<T> next;
public Node(T data){
this.data = data;
this.next = next;
}
}
public void add(T data){
Node<T> nn = new Node<T>(data);
nn.next = first;
first = nn;
}
public boolean findValue(T key){
Node current = first;
while(current != null){
if(current.data == key)
return true;
else
current = current.next;
}
return false;
}
}
答案 0 :(得分:7)
==
运算符比较两个对象引用以查看它们是否引用同一对象。使用Integer
值时,JVM会将Integer
从-128
缓存到127
。
此方法将始终缓存-128到127(包括端点)范围内的值,并可以缓存此范围之外的其他值。
当10
和99
加框时,当另一个Integer
和10
装箱时,它们会分别产生相同的99
对象。但是,装箱Integer
和990
这样的非缓存10000
对象每次都会产生不同的Integer
个对象。
将==
替换为equals
方法,以比较关键内容,而不是关键参考。
if(current.data != null && current.data.equals(key))
答案 1 :(得分:2)
在检查您是否找到了您正在寻找的价值时,您应该使用.equals()而不是==:
public boolean findValue(T key){
Node current = first;
while(current != null){
if(current.data != null && current.data.equals(key))
return true;
else
current = current.next;
}
return false;
}
当您将LinkedList声明为整数列表时,您的原始int在存储在节点中之前将包装在Integer对象中。因此==并不总是有效,因为你没有比较两个基元。
答案 2 :(得分:1)
你的问题是你正在使用==而不是等于 它适用于作为基本类型的int,但对于Integer(object)==仅当两个成员是同一个实例时才返回true。
答案 3 :(得分:0)
为了成为“通用”,你应该使用equals方法而不是== operator。