pizza
pizza

Reputation: 732

Java compareTo for LinkedList

public class Node<E> {
    private E data;
    private Node<E> next;
    public Node<E>(){
        next = null;
    }
    public Node(E dataIn){
    data = dataIn;
    }       
}

///

class LinkedList<E>{
    public void insert(E dataIn){
            if(ctr != 0){
                Node<E> temp = new Node<E>(dataIn);
                Node<E> cursor = head;
                Node<E> prev = cursor;
                while(cursor != null && cursor.data.compareTo(dataIn) < 0){
                        prev = cursor;
                        cursor = cursor.next;
                }
                prev.next = temp;
                temp.next = cursor;
             }
             else
                add(dataIn);
             ++ctr;  
   }
}

In my insert function, how do I let Java know that cursor.data is the same type as the dataIn ?(Let's say they are both Integers) Sorry I apologize for this dumb question. I am a noob and I have no idea where to write 'compareTo' function because I am using Integer ,not a custom data type. So, when I compile the code, I get this error

required: E#1
found: no arguments
reason: actual and formal argument lists differ in length
where E#1,E#2 are type-variables:
E#1 extends Object declared in class LinkedList
E#2 extends Object declared in class Node
LinkedList.java:34: error: cannot find symbol
        while(cursor != null && cursor.data.compareTo(dataIn) < 0){
                                           ^
symbol:   method compareTo(E#1)
location: variable data of type E#2
where E#1,E#2 are type-variables:
E#1 extends Object declared in class LinkedList
E#2 extends Object declared in class Node

Thank you in advance for your attention.!

Upvotes: 1

Views: 114

Answers (1)

Maxim
Maxim

Reputation: 1254

Define the list class in the following way

public class LinkedList<E extends Comparable<E>> {

    private static class Node<E> {

and make sure that the Node class is nested static (can be private, package-private in this case). After that it's would be possible to add any type which implements Comparable into the linked list.

Upvotes: 3

Related Questions