import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class MapDemo {
public static void main(String[] args) {
//HashMethod();
TreeMethod();
}
/*
* TreeMap中的元素可以排列顺序,构造时用比较器或者实现Comparable接口
*/
private static void TreeMethod() {
Map<Student1,String> map = new TreeMap<Student1,String>(new StuNamComp());
map.put(new Student1("acc",10),"beijing");
map.put(new Student1("aaa",12),"wuhan");
map.put(new Student1("abc",14),"shanghai");
Set<Student1> keySet = map.keySet();
for(Iterator<Student1> it = keySet.iterator();it.hasNext();) {
Student1 stu = it.next();
System.out.println(stu + map.get(stu));
}
System.out.println("==============================");
Set<Map.Entry<Student1, String>> entrySet = map.entrySet();
for(Iterator<Map.Entry<Student1, String>> it = entrySet.iterator();it.hasNext();) {
Map.Entry<Student1, String> me = it.next();
System.out.println(me.getKey() + me.getValue());
}
}
/*
* HashMap中的元素无序(存入和指定的位置不保证一致),按照哈希表存储
*/
private static void HashMethod() {
Map<Student1,String> map = new HashMap<Student1,String>();
map.put(new Student1("zhangsan",10),"beijing");
map.put(new Student1("lisi",12),"wuhan");
map.put(new Student1("wangwu",14),"shanghai");
Set<Student1> keySet = map.keySet();
for(Iterator<Student1> it = keySet.iterator();it.hasNext();) {
Student1 stu = it.next();
System.out.println(stu + map.get(stu));
}
System.out.println("==============================");
Set<Map.Entry<Student1, String>> entrySet = map.entrySet();
for(Iterator<Map.Entry<Student1, String>> it = entrySet.iterator();it.hasNext();) {
Map.Entry<Student1, String> me = it.next();
System.out.println(me.getKey() + me.getValue());
}
}
}
class StuNamComp implements Comparator<Student1> {
@Override
public int compare(Student1 o1, Student1 o2) {
int num = o1.name.compareTo(o2.name);
if(num == 0)
return new Integer(o1.age).compareTo(new Integer(o2.age));
return num;
}
}
class Student1 implements Comparable<Student1>{
String name;
int age;
Student1(String name,int age) {
this.name = name;
this.age = age;
}
@Override
public int hashCode() {
return this.name.hashCode() * this.age * 20;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof Student1)) {
throw new ClassCastException("类型错误");
}
Student1 stu = (Student1) obj;
return this.name.equals(stu.name) && this.age == stu.age;
}
@Override
public String toString() {
return this.name + ".." + age;
}
@Override
public int compareTo(Student1 o) {
int num = new Integer(this.age).compareTo(new Integer(o.age));
if(num == 0) {
return this.name.compareTo(o.name);
}
return num;
}
}
java Map集合练习
最新推荐文章于 2024-12-11 14:46:19 发布