I am trying to implement a generic ADT in Java, similar to a linked list. I had a problem when it is instantiated as Integer, because Find(E e) method fails in the comparison. It happens for values greater than 127. I suppose that it is caused by an implicit byte casting. I don't know how to fix the error and preserve the generic feature.
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;
}
}
//...
}
Main:
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"));
Output:
1
-1
1
public class NodoDoble<E> {
public E value;
public NodoDoble<E> next;
public NodoDoble<E> prev;
}
Solved!!!
Use Object casting and compare using "equals"
if( ((Object)iterator.value).equals(e)){
return i;
} else {
iterator = iterator.next;
i++;
}
}