Problems using compareTo


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 11 of 11

Thread: Problems using compareTo

  1. #1
    Join Date
    Jan 2007
    Posts
    60

    Problems using compareTo

    I have rewritten my previous code for my linked list and have it all compiling apart from the problem with the compareTo

    I am trying to compare objects for sorting and if an object being added is null, throw it out.

    On the Node class which creates the Node object, I am using compareTo and equals but get these errors when compiling

    cannot find symbol
    symbol : method compareTo(java.lang.Object)
    location: class java.lang.Object
    int nodeComp = cargo.compareTo(newNode.getContents());
    incomparable types: boolean and <nulltype>
    if ((obj instanceof Node) == null) {
    Here is the code for the Node class

    Code:
    import java.util.*;
    
    public class Node {
      Node next;             // Refers to next item in the list.
      Node previous;         // Refers to the previous item.       ***
      Object cargo;               // The item for this Node.
    
      // Constructor: 
      public Node(Object item) {
        this.cargo = cargo;        // Store the item.
        next = null;  // Set next and previous to null.      ***
        previous = null;
      }
    
      // Set the pointer to the next Node:
      public void setNext(Node next) {
        this.next = next;        // Store reference to the next item.
      }
      
      // Additional method to set the pointer to the previous Node:  ***
      public void setPrevious(Node previous) {                                                               
        this.previous = previous; // Store reference to the previous item. 
      }
     
      // Get the next item in the list:
      public Node getNext() {
        return next;
      }
    
      // Additional method to get the previous item in the list:         ***
      public Node getPrevious() {
        return previous;
      }
    
      // Get the object for this item:
      public Object getContents() {
        return cargo;
      }
    
      // Return class name & object:
      public String toString() {
        return "Node " + cargo;
      }
    
      public int compareTo(Object obj) {
        Node newNode = (Node) obj;
        int nodeComp = cargo.compareTo(newNode.getContents());
    
        return nodeComp = 0;
      }
    
      public boolean equals(Object obj) {
        if (!(obj instanceof Node)) {
          return false;
        }
        if ((obj instanceof Node) == null) {
          throw new NullPointerException();
        }
        Node newNode = (Node) obj;
        return cargo.equals(newNode.getContents());
      }
    }
    If someone could tell me how to compare objects, I would be very grateful. I need to make this generic which shouldn't be a problem

    Another question is, when this is working and comparing objects and throwing null objects and duplicates, on my LinkedList class, to implement the SortededSet interface, would I still need to use Comparator as it is already comparing in the Node class.

    I have included the files as text files if someone could please have a look and help.

    I want to implement the SortedSet interface on my Linked List with an Iterator which compiles and the other methods shouldn't be a problem apart from how I would write the method for the Comparator.
    Attached Files Attached Files

  2. #2
    Join Date
    Dec 2004
    Location
    San Bernardino County, California
    Posts
    1,468
    You are going to run into problems by defining cargo as an Object. Objects compare by the address of the memory location. You need to know what the datatype of the cargo is, and then compare the values held in (referred to) each element - you need to cast the cargo to its proper data type [remember that all instances of all classes are Objects, so you can cast down to its datatype if it is an instanceOf.

  3. #3
    Join Date
    Jan 2007
    Posts
    60
    I have made some improvements and I have not turned it into a sorted set but I don't know what to put for the subSet(), headSet() and tailSet() methods. they are all supposed to return something but i don't know how to return what is needed.

    As for the cargo being an object, i need it to take anything but the objects need to be comparable and not accept null elements and duplicates.

    I have included my updated classes if you could please have a look and help me finish.

    Oh, and by the way, when i have it working, I shall be making it generic
    Attached Files Attached Files

  4. #4
    Join Date
    Mar 2007
    Location
    Bangalore, India
    Posts
    247
    1) Does the object Cargo have a compareTo method? Otherwise it will not work.
    2) If it does have compareTo, make sure that it implements the Comparable interface (java.lang.Comparable). It is only to mark the object as Comparable, and does not do anything by itself.
    3) Cast cargo to Comparable like so:
    int nodeComp = ((Comparable)cargo).compareTo(newNode.getContents());
    This will work only if the object pointed to by cargo implements Comparable.
    4) It is a good idea to have Node implement Comparable too.

    Then your first example should work. The second example you have sent is incorrect. You don't do a toString() and compare, you compare the field values. And it is best done by the object (cargo) itself, and not in node.

  5. #5
    Join Date
    Mar 2007
    Location
    Bangalore, India
    Posts
    247
    Also change
    return nodeComp = 0;
    to
    return nodeComp;

  6. #6
    Join Date
    Jan 2007
    Posts
    60
    Thanks Razee

    I made those changes and it compiles but can you please check my code to make sure I have done it properly? I'm not sure if if i have implemented comparable correctly

    This is my Node class again
    Code:
    import java.util.*;
    
    public class Node implements Comparable{
    	Node next;             // Refers to next item in the list.
    	Node previous;         // Refers to the previous item.       ***
    	Object cargo;               // The item for this Node.
    
    	// Constructor: 
    	public Node(Object cargo) {
    		this.cargo = cargo;        // Store the item.
    		next = null;  // Set next and previous to null.      ***
    		previous = null;
      	}
    
      	// Set the pointer to the next Node:
        public void setNext(Node next) {
            this.next = next;        // Store reference to the next item.
        }
      
        // Additional method to set the pointer to the previous Node:  ***
        public void setPrevious(Node previous) {                                                               
            this.previous = previous; // Store reference to the previous item. 
        }
     
        // Get the next item in the list:
        public Node getNext() {
            return next;
        }
    
        // Additional method to get the previous item in the list:         ***
        public Node getPrevious() {
            return previous;
        }
    
        // Get the object for this item:
        public Object getContents() {
            return cargo;
        }
    
        // Return class name & object:
        public String toString() {
            return ""+ cargo;
        }
    
        public int compareTo(Object obj) {
        	Node newNode = (Node) obj;
        	int nodeComp = ((Comparable)cargo).compareTo(newNode.getContents());
    
        	return nodeComp;
        }
    
        public boolean equals(Object obj) {
        	if (!(obj instanceof Node)) {
           	    return false;
            }
        
        	Node newNode = (Node) obj;
        	return cargo.equals(newNode.getContents());
        }
    }
    and here is my Linked List class which implements the SortedSet interface
    Code:
    import java.util.*;
    
    public class OrderedLinkedList extends AbstractSet implements SortedSet {
        
        private Node start;
        private Node end;
        private Node current;
      
        private int numberContents;
    
        public OrderedLinkedList() {
        	
        	numberContents = 0;
        }
    
        public OrderedLinkedList(Object cargo) {
    
        	start = new Node(cargo);
        	end = start;
        	numberContents = 1;
        }
    
        public boolean add(Object cargo) {
            
        	Node newEnd = new Node(cargo);
        	
        	if (numberContents == 0 ) {
        		start = newEnd;
        	}
        	else {
    		end.setNext(newEnd);
        		newEnd.setPrevious(end);
        		current = newEnd;
        		end = newEnd; 	
        	}
        	numberContents++;
        	return true;
        }
    
        public int size() {
            return numberContents;
        }
    	
        public boolean isEmpty() {
            return start == null;
        }
    	
        public Object first() {
            if (isEmpty()) {
                throw new NoSuchElementException();
            }
            current = start;
            return start.getContents();
        }
    
        public Object last() {
            if (isEmpty()) {
                throw new NoSuchElementException();
            }
            current = end;
            return end.getContents();
        }
            
          	
      	public SortedSet tailSet(Object fromElement) {
      		return null;		
      	}
      	
      	public SortedSet headSet(Object toElement) {
      		return null;
      	}
      	
      	public SortedSet subSet(Object fromElement, Object toElement) {
      		return null;
      	}  	
      		
        public Iterator iterator() {
        	
            return new Iterator() {
            	
                Object valueReturned;
                private int counter = 0;
                
                public boolean hasNext() {
                    if (counter >= numberContents){
                        return false;
                    }
                    else {
                        counter++;
                        return true;
                    }
                }
                
                public Object next() {
                    valueReturned = current.getContents();
                    current = current.getNext();
                    return valueReturned;
                }
                
                public void remove() {
                    throw new UnsupportedOperationException();
                }     
            };
        } 
        	
        public Comparator comparator() {
        
        	return new Comparator() {
      	
        		public int compare(Object obj1, Object obj2) {
        			Node node1 = (Node) obj1;
        			Node node2 = (Node) obj2;
     	
     				return node1.compareTo(node2);
        		}	
    
        		public boolean equals(Object obj) {
            		if (!(obj instanceof Node)) {
                		return false;
            		}
    
            		Node newNode = (Node) obj;
            		return current.getContents().equals(newNode.getContents());
        		}
        	};
        }       
    }
    This compiles fine but I have done the subSet(), headSet() and tailSet() methods......have you any idea what I have to return in those methods?

    Many thanks for all your help so far

  7. #7
    Join Date
    Dec 2004
    Location
    San Bernardino County, California
    Posts
    1,468
    Have you actually used this code with any data?

    It seems to me that you are going to have problems with cargo defined as an Object.

  8. #8
    Join Date
    Jan 2007
    Posts
    60
    I haven't tested it yet properly but i did try the other day and it threw a null pointer exception. What it needs to do is, take a list of objects such as integers, doubles or characters/words and sort them asecnding but the object must be of the same type when creating the list

  9. #9
    Join Date
    Jan 2007
    Posts
    60
    I think but am not sure if I have done this right but I think i have made the 2 classes generic.

    I have compiled my Node class and it compiles fine

    When I try to compile my Linked List class, I get 4 errors. of them are to do with the subSet, headSet and tailSet and I think I have done it properly but with no real goods examples online, i'm not sure if it is right. The other errro is to do with the compare() method.

    Here are the errors:

    non-static method tailSet(E) cannot be referenced from a static context
    SortedSet<E> tail = OrderedLinkedList.tailSet(fromElement+"\0");
    non-static method headSet(E) cannot be referenced from a static context
    SortedSet<E> head = OrderedLinkedList.headSet(toElement+"\0");
    non-static method subSet(E,E) cannot be referenced from a static context
    SortedSet<E> sub = OrderedLinkedList.subSet(fromElement, toElement+"\0");
    compareTo(E) in Node<E> cannot be applied to (Node<E>)
    return node1.compareTo(node2);
    ^
    Have I done those methods correctly and why am I getting the last error?

    I have included the updated files again. Any help much appreciated
    Attached Files Attached Files

  10. #10
    Join Date
    Dec 2004
    Location
    San Bernardino County, California
    Posts
    1,468
    Your "static context" error message results from your mixture of an instance variable (a particular element of a particular linked list) to a method of the class rather than the particular linked list's method. tailSet is not a static method, so you must call the particular instance's method (for example, myList.tailSet( Element ) ) to get the tail set of that particular linked list.

    Your last error message is telling you that you cannot compare an Element held in a node with another Node itself (rather than the element contained in that other Node). It is common practice to have an element() method of a Node class which returns the element contained in the node, so you can compare an element with the element returned by the call to nextNode.element() [remember to keep in mind the non-static nature of this call ...]

  11. #11
    Join Date
    Jan 2007
    Posts
    60
    I think I have fixed that by using

    Code:
    public SortedSet<E> tailSet(E fromElement) {
            
            if (isEmpty()) {
                throw new NullPointerException();
            }
            OrderedLinkedList oll = new OrderedLinkedList();
            
            SortedSet<E> tail = oll.tailSet(fromElement+"\0");
            return tail;
            	
        }
    here is the code for the other problem

    Code:
    public int compare(E obj1, E obj2) {
                    Node<E> node1 = (Node) obj1;
        			Node<E> node2 = (Node) obj2;
                    
         			return node1.compareTo(node2);            
                }
    which I changed to in the compare method

    Code:
    public Comparator<E> comparator() {
        
        	return new Comparator<E>() {
      	
                public int compare(E obj1, E obj2) {
                    Node<E> node1 = (Node) obj1;
        			Node<E> node2 = (Node) obj2;
                    
         			return node1.compareTo(node2.getContents());            
                }	
    
                public boolean equals(E obj) {
            	if (!(obj instanceof Node)) {
                        return false;
            	}
    
            	Node<E> newNode = (Node<E>) obj;
            	return current.getContents().equals(newNode.getContents());
                }
        	};
        }
    and this no longer causes a problem when compiling (is this right?)

    I do however have another problem

    name clash: equals(E) in and equals(java.lang.Object) in java.lang.Object have the same erasure, yet neither overrides the other
    How do i override the equals method with the one i have written?
    Last edited by AdRock; 01-24-2008 at 02:42 PM.

Similar Threads

  1. extFloodFill problems...
    By RobertSteiner in forum VB Classic
    Replies: 0
    Last Post: 11-28-2006, 09:52 AM
  2. SkipList problems
    By Rhett77 in forum Java
    Replies: 1
    Last Post: 11-24-2006, 05:09 PM
  3. Problems with MSSQLServer and Java
    By jlopes151 in forum Database
    Replies: 1
    Last Post: 11-21-2005, 05:32 AM
  4. Replies: 0
    Last Post: 07-19-2002, 02:41 AM
  5. Replies: 0
    Last Post: 10-04-2000, 05:05 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center