Results 1 to 2 of 2
  1. #1
    j2me64's Avatar
    j2me64 is offline Senior Member
    Join Date
    Sep 2009
    Location
    Zurich, Switzerland
    Posts
    962
    Rep Power
    6

    Default problems with a TreeSet

    i'm implementing a TreeSet, but when i try to add the second element i got NullPointerException and i can't figure out why:confused:. here is my class Month

    Java Code:
    package navigableset;
    
    public class Month implements Comparable<Month> {
    	private String name;
    	private String number;
    	
    	public Month(int i, String name) {
    		this.number = number;
    		this.name = name;
    	}
    		
    	public int compareTo(Month m) {
    		return this.number.compareTo(m.number);
    	}
    	
    }

    and here is the class with the main() and where the error happen is when i try to add the object feb:

    Java Code:
    package navigableset;
    
    import java.util.NavigableSet;
    import java.util.TreeSet;
    
    public class TreeSetExample {
    
    	public static void main(String[] args) {
    
    		NavigableSet<Month> set = new TreeSet<Month>();
    		Month jan = new Month(1, "January");
    		Month feb = new Month(2, "February");
    		
    		set.add(jan);
    		set.add(feb);
    	}
    }

  2. #2
    j2me64's Avatar
    j2me64 is offline Senior Member
    Join Date
    Sep 2009
    Location
    Zurich, Switzerland
    Posts
    962
    Rep Power
    6

    Default

    Quote Originally Posted by j2me64 View Post
    i'm implementing a TreeSet, but when i try to add the second element i got NullPointerException and i can't figure out why:confused:.

    the bugs were in the class Month, so changing to

    Java Code:
    public class Month implements Comparable<Month> {
    	private String name;
    	private int number;
    	
    	public Month(int i, String name) {
    		this.number = i;
    		this.name = name;
    	}
    		
    	public int compareTo(Month m) {
    		Integer i1 = this.number;
    		Integer i2 = m.number;
    		return i1.compareTo(i2);
    	}
    }

    also the TreeSet is happy now.
    Last edited by j2me64; 01-10-2011 at 04:54 PM.

Similar Threads

  1. Please Help - TreeSet
    By Riftara in forum New To Java
    Replies: 1
    Last Post: 10-21-2010, 09:33 PM
  2. Having trouble removing from TreeSet
    By xtrmi in forum New To Java
    Replies: 2
    Last Post: 05-02-2009, 05:01 AM
  3. TreeSet Demonstration
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-15-2008, 08:34 PM
  4. ClassCastException in TreeSet
    By pHew in forum New To Java
    Replies: 2
    Last Post: 01-16-2008, 01:20 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
  •