繁体   English   中英

打印 TreeSet 时出现 ArrayIndexOutOfBoundsException

[英]ArrayIndexOutOfBoundsException while printing a TreeSet

我想为抽象 class 创建一个树集。 当我尝试在树集中打印 [0] 的值时,output 正确给出1 ,但 [1] 的 output 给出错误:

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

有人可以帮我解决这个问题吗?

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

在 Employee class 内部的 compareTo 方法中,您应该比较 empId,而不是您创建但从未初始化的这个 int id。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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