java Map接口TreeMap涉及类的比较
*类的比较需要实现接口Comparable和重写接口的抽象方法compareTo():
*class em implements Comparable<em> //需要增加类对象的泛型
public int compareTo(em o) //负数小于,0等于,正数大于
Map<em,String> treemap2=new TreeMap<>(); //按照类中的方法递增 treemap2.put(new em(2,"af",30),"yes1"); treemap2.put(new em(1,"af",30),"yes2"); treemap2.put(new em(6,"af",30),"yes3"); treemap2.put(new em(5,"af",30),"yes4"); for(em f:treemap2.keySet()) { System.out.println(f+"+"+treemap2.get(f) ); }class em implements Comparable<em>{ //比较类时需要实现Comparable接口,泛型是对象 int id; String name; double salary; public em(int id, String name, double salary) { super(); this.id = id; this.name = name; this.salary = salary; } @Override public int compareTo(em o) { //负数小于,0等于,正数大于 if(this.salary>o.salary) { return 1; } else if(this.salary<o.salary) { return -1; } else { if(this.id>o.id) { return 1; } else if(this.id<o.id) { return -1; } else { return 0; } } }
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。