简体   繁体   中英

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;
    }   
  }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM