/*
Map--
|--Hashtable:底层是哈希表数据结构,不可以存入null键null值。线程同步。
|--HashMap:底层是哈希表数据结构,可以存入null键null值。线程不同步。
|--TreeMap:底层是二叉树数据结构,线程不同步。可以给键排序
*/
package pack;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/*public class Main {
public static void main(String[] args) {
Map<Integer,String> map = new HashMap<Integer,String>();
map.put(1, "java1"); //增
map.put(2, "java2");
map.put(3, "java3");
map.remove(4); //删
//sys(map.containsKey(1)); //判
//sys(map.get(2)); //查
//sys(map);
查方法一:通过Set集合中的迭代器得到键,再通过get方法得到值
Set<Integer> s = map.keySet();
for(Iterator<Integer> it = s.iterator();it.hasNext(); ) {
sys(map.get(it.next()));
}
Collection coll = map.values();
for(Iterator<Integer> it = coll.iterator();it.hasNext(); ) {
sys(it.next());
}
sys("---------------");
查方法二:将Map集合中的映射关系取出,存到Set集合中
Set<Map.Entry<Integer, String>> entryset = map.entrySet();
Iterator<Map.Entry<Integer, String>> it = entryset.iterator();
while(it.hasNext()) {
Map.Entry<Integer, String> me = it.next();
sys(me.getValue());
sys(me.getKey());
}
}
public static void sys(Object obj) {
System.out.println(obj);
}
}*/
/*在TreeSet中传入对象参数,按年龄排序*/
public class Main {
public static void main(String[] args) {
TreeMap<Person,Integer> ts = new TreeMap<Person,Integer>(new MyComparator());
ts.put(new Person("java1",1), 01);
ts.put(new Person("java3",3), 03);
ts.put(new Person("java2",2), 02);
ts.put(new Person("java4",4), 04);
Set<Map.Entry<Person,Integer>> entryset = ts.entrySet();
Iterator<Map.Entry<Person,Integer>> it = entryset.iterator();
while(it.hasNext()) {
Map.Entry<Person,Integer> me = it.next();
Person per = me.getKey();
Integer age1 = me.getValue();
sys(per+"..."+age1);
}
}
public static void sys(Object obj) {
System.out.println(obj);
}
}
class Person {
private String name;
private int age;
Person(String name,int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
}
class MyComparator implements Comparator<Person> {
public int compare(Person p1,Person p2) {
int a = new Integer(p1.getAge()).compareTo(new Integer(p2.getAge()));
if(a==0) { //比较与前面行的区别,Integer与String有compareTo方法,而int没有
return p1.getName().compareTo(p2.getName());
}
return a;
}
}
原文地址:http://blog.csdn.net/sjtu_chenchen/article/details/45227259