整数比较的通用数据结构问题

问题描述

我正在尝试用 Java 实现一个通用的 ADT,类似于链表。当它被实例化为整数时,我遇到了问题,因为 Find(E e) 方法在比较中失败。它发生在大于 127 的值上。我想这是由隐式字节转换引起的。我不知道如何修复错误并保留通用功能

public class MyList<E> {
    private Nododoble<E> head;
    private Nododoble<E> tail;
    private int size;
    public MyList(){...}
    public boolean IsEmpty(){...}
    public int Size(){...}
    public void Clear(){...}
    public boolean Add(E e)
    public E Get(int index){...}  
    public boolean Add(E e,int pos){...}
    public int Find(E e){
        Nododoble<E> iterator = head;
        int i = 0;
        while (i < size && !found) { 
            if( iterator.value == e){
                return i;
            } else {
                iterator = iterator.next;
                i++;
            }        
        }
            return -1;
        }
    }
//...
}

主要内容

MyList<Integer> L1 = new MyList<>();
L1.Add(45);
L1.Add(120);
L1.Add(130);
System.out.println(L1.Find(120));
System.out.println(L1.Find(130));
MyList<String> L2 = new MyList<>();
L2.Add("dog");
L2.Add("cat");
System.out.println(L2.Find("cat"));

输出

1
-1
1
public class Nododoble<E> {
    public E value;
    public Nododoble<E> next;
    public Nododoble<E> prev;
}

解决方法

解决了!!!

使用对象转换并使用“等于”进行比较

if( ((Object)iterator.value).equals(e)){
        return i;
    } else {
        iterator = iterator.next;
        i++;
    }
}