Map分为两种:HashMap和TreeMap
HashMap:(Person类就不写了,给你主要部分)
public class MapDemo {
public static void main(String[] args) {
//创建集合
Map<String,Person> map = new HashMap<String,Person>();
//创建自定义对象
Person p1 = new Person("AAA",21);
Person p2 = new Person("BBB",22);
Person p3 = new Person("CCC",23);
Person p4 = new Person("DDD",24);
Person p5 = new Person("EEE",25);
Person p6 = new Person("FFF",26);
//添加元素
map.put("1:",p1);
map.put("2:",p2);
map.put("3:",p3);
map.put("4:",p4);
map.put("5:",p5);
map.put("6:",p6);
//遍历集合元素
Set<Map.Entry<String,Person>> set = map.entrySet();
Iterator<Map.Entry<String,Person>> it = set.iterator();
while(it.hasNext()){
Map.Entry<String,Person> m = it.next();
String key = m.getKey();
Person value = m.getValue();
System.out.println(key+value);
}
}
}
TreeMap:
/*
* TreeMap保证元素的唯一性
* 用Comparetor接口实现compare方法(比较器)
* 比较器比较的是key,String是固定不变的所以没有必要比较,用TreeMap<Person,String>
*/
public class TreeMapDemo {
public static void main(String[] args) {
//创建集合对象
TreeMap<Person,String> ts = new TreeMap<Person,String>(new Comparator<Person>() {
public int compare(Person p1,Person p2) {
int num = p1.getNum()-p2.getNum();
int num2 = (num==0)?(p1.getName().compareTo(p2.getName())):num;
return num2;
}
});
//创建自定义元素
Person p1 = new Person("孔子", 45);
Person p2 = new Person("老子", 56);
Person p3 = new Person("孟子", 50);
Person p4 = new Person("孙子", 40);
Person p5 = new Person("庄子", 43);
Person p6 = new Person("孟子", 50);
Person p7 = new Person("孙子", 40);
//添加元素
ts.put(p1,"1hao");
ts.put(p2,"2hao");
ts.put(p3,"3hao");
ts.put(p4,"4hao");
ts.put(p5,"5hao");
ts.put(p6,"6hao");
ts.put(p7,"7hao");
//遍历
Set<Map.Entry<Person,String>> set = ts.entrySet();
Iterator<Map.Entry<Person,String>> it = set.iterator();
while(it.hasNext()){
//再遍历Map.Entry
Map.Entry<Person,String> m = it.next();
Person key = m.getKey();
String value = m.getValue();
System.out.println(key+"***"+value);
}
}
}
|