javaarraysabstract-classtreelist

ArrayIndexOutOfBoundsException while printing a TreeSet


I want to create a Treeset for abstract class. When I'm trying to print the value for the [0] in the treeset the output is giving 1 correctly but the output for [1] it is giving error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1

Can someone please help me resolve this?

public abstract class E implements Comparable<E>{
    private int Id;
    private String name;

    public E(int Id, String name) {
        this.Id = Id;
        this.name = name;
    }
    int id;
    public int compareTo(E b) {  
        if(id>b.id){  
            return 1;  
        }else if(id<b.id){  
            return -1;  
        }else{  
        return 0;  
        }  
    }   
    public int getId() {
        return Id;
    }   
    public String Name() {
        return name;
    }   
  }

Solution

  • In your compareTo method inside Employee class you should compare empId, not this int id that you creating and never initializing.