不明白为什么我的通用代码不起作用

ixx*_*686 -1 java generics generic-type-argument

下面是链表的简单实现.我刚刚添加了相关代码.首先,我在列表中添加了一些值,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;
    }
}
Run Code Online (Sandbox Code Playgroud)

rge*_*man 7

==运算符比较两个对象的引用,看看他们是否指向同一个对象.随着Integer值时,JVM将缓存Integer从s -128通过127.

来自Integer.valueOfjavadocs:

此方法将始终缓存-128到127(包括端点)范围内的值,并可以缓存此范围之外的其他值.

1099被装箱时,它们Integer(分别)在另一个时产生相同的对象10并被99装箱.不过,拳击非缓存的Integer对象,比如99010000会导致不同的Integer每次对象.

更换==equals的方法,比较关键的内容,而不是关键引用.

if(current.data != null && current.data.equals(key))
Run Code Online (Sandbox Code Playgroud)