java中先自定义一个类,然后使用map接口,懂的人进啊! 5
importjava.util.*;classUserimplementsComparable<User>{intid;Stringname;intage;publicU...
import java.util.*;
class User implements Comparable<User>{
int id;
String name;
int age;
public User(int id ,String name,int age){
this.id = id;
this.name= name;
this.age = age;
}
public String toString(){
return "User@id:"+this.id+"-name:"+this.name+"-age:"+this.age;
}
public int compareTo(User u){
return new Integer(u.id).compareTo(this.id);
}
}
public class TreeMapDemo2 {
public static void main(String[] args) {
//如果TreeMap的key存储的是自定义类型对象,需要我们自己实现排序规则
//排序规则参考TreeSet
TreeMap<User,User> map = new TreeMap<User,User>();
User u3 = new User(3,"C",20);
User u1 = new User(1,"A",21);
User u4 = new User(4,"D",22);
User u2 = new User(2,"B",23);
map.put(u3,u3);
map.put(u1,u1);
map.put(u4,u4);
map.put(u2,u2);
System.out.println(map);
}
}
我主要是不明白为什么 put(u3,u3),为什么key和value一样都是u3啊,谁能和我解释一下啊 展开
class User implements Comparable<User>{
int id;
String name;
int age;
public User(int id ,String name,int age){
this.id = id;
this.name= name;
this.age = age;
}
public String toString(){
return "User@id:"+this.id+"-name:"+this.name+"-age:"+this.age;
}
public int compareTo(User u){
return new Integer(u.id).compareTo(this.id);
}
}
public class TreeMapDemo2 {
public static void main(String[] args) {
//如果TreeMap的key存储的是自定义类型对象,需要我们自己实现排序规则
//排序规则参考TreeSet
TreeMap<User,User> map = new TreeMap<User,User>();
User u3 = new User(3,"C",20);
User u1 = new User(1,"A",21);
User u4 = new User(4,"D",22);
User u2 = new User(2,"B",23);
map.put(u3,u3);
map.put(u1,u1);
map.put(u4,u4);
map.put(u2,u2);
System.out.println(map);
}
}
我主要是不明白为什么 put(u3,u3),为什么key和value一样都是u3啊,谁能和我解释一下啊 展开
2个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询