I have the following code, how can I use the compareTo method with primitive types:
public class mySortertedList<T extends Comparable<T>> extends myLinkedList<T> {
class Node {
Node next = null;
T data;
Node (T x) {
data = x;
}
}
public int compareTo (T Obj) {
return this.compareTo(Obj);
}
Basically what I have is a sorted linked list which adds values to the list based on the compareTo method. How can I make sure that the compareTo works for primitive types, at least Integers? Any help is highly appreciated!
EDIT: To clarify, here is more code: The main programme :
public static void main(String[] args) {
newList.addTo(4);
newList.addTo(1337);
newList.addTo(30);
newList.addTo(15);
}
I also have other methods like get(int index), remove() i.e. removes the last element in the list. Here is the addTo method from mySortertList<T extends Comparable> class, there is a declaration of variable start of type Node, it is really just a pointer as a starting point to go through the whole linked list one by one:
private Node start = null;
public void addTo(T x) {
Node newNode = new Node(x);
Node pointer = start;
if (start == null) {
start = newNode;
} else if (size()==1){
if (newNode.data.compareTo(start.data)<0) {
newNode.next= start;
start = newNode;
} else {
start.next= newNode;
}
} else {
boolean valuePlaced= false;
Node pointer2= start.next;
while (pointer2 !=null) {
if (newNode.data.compareTo(pointer.data)<0) {
newNode.next= start.next;
start.next = newNode;
valuePlaced = true;
} else if (newNode.data.compareTo(pointer2.data)<0) {
pointer = newNode;
new.next= pointer2;
valuePlaced = true;
}
pointer = pointer.next;
pointer2 = pointer2.next;
}
if (valuePlaced == false) {
pointer.next= newNode;
}
}
}