一是Map兩種遍歷方式究竟有什麼區別?
二是兩種比較方式有什麼區別?(比較性Compatable和比較器Comparator)
詳細情況請看代碼以及代碼註釋
import java.util.*;
import static java.lang.System.*;
/*
需求:對學生對象的年齡進行升序排序,因爲數據是以鍵值對的形式存在,所以要使用可以排序的Map集合——TreeMap
*/
class TreeMapDemo
{
publicstatic void main(String[] args)
{
TreeMap<Student,String>tm = new TreeMap<Student,String>(new MyComparator());
tm.put(newStudent("zhangsan3",23),"nanjin");
tm.put(newStudent("zhangsan2",22),"shanghai");
tm.put(newStudent("zhangsan4",22),"tianjin");
tm.put(newStudent("zhangsan1",21),"beijin");
/*
Map遍歷有兩種方法,setKey()和Map.entrySet(),他們都可以遍歷Map,但是在速度上有差別。
setKey()的速度較慢,因爲他實際上遍歷了兩遍,第一遍的時候取出key,第二遍的時候通過key的set集合取出所有value。
Map.entrySet()速度較快,因爲它只遍歷了一遍。
所以推薦使用第二種方法。
*/
//使用第二種遍歷方法
Set<Map.Entry<Student,String>>entrySet = tm.entrySet();
Iterator<Map.Entry<Student,String>>it = entrySet.iterator();
while(it.hasNext())
{
Map.Entry<Student,String>me = it.next();
out.println(me.getKey()+"_"+me.getValue());
}
}
}
//定義學生類
class Student implements Comparable
{
privateString name;
privateint age;
Student(Stringname,int age)
{
this.name= name;
this.age= age;
}
publicString getName()
{
returnthis.name;
}
publicint getAge()
{
returnthis.age;
}
publicint compareTo(Object obj)
{
if(!(obj instanceof Student))
{
thrownew ClassCastException("不是學生類");
}
Studentst = (Student)obj;
intnum = this.age-st.getAge();
if(num == 0)
{
returnthis.name.compareTo(st.getName());
}
returnnum;
}
publicString toString()
{
return this.name+","+this.age;
}
}
/*
Comparable和Comparator的區別:
1.Compatable是通用的接口,用戶可以通過實現它的compareTo()方法來完成自己的特定比較。
而Comparator可以看成一種算法的實現,在容器集合collection需要比較功能的時候,來指定這個比較器,這可以看成一種設計模式(策略模式),將算法和設計分離。
2.前者比較固定,和一個具體類相綁定,而後者比較靈活,它可以被用於各個需要比較功能的類使用。
可以說前者屬於靜態綁定,而後者屬於動態綁定。
3.一個類實現了Comparable接口標明這個類的對象之間是可以互相比較的。如果用數學語言描述的話就是這個類的對象組成的集合中存在一個全序。
這樣,這個類對象組成的集合就可以使.用.Sort.方.法.排序了.
4.而Comparato的作用有兩個:
a.如果類的設計師沒有考慮到Compare的問題而沒有實現Comparable接口,可以通過Comparator來實現比較算法進行排序。
b.可以更加靈活的實現排序規則,爲了使用不同的排序標準做準備,比如升序,降序,或者將來想通過類的其他字段進行排序。
*/
//自定義比較器,使年齡按照倒序排列
class MyComparator implementsComparator<Student>
{
publicint compare(Student st1,Student st2)
{
intnum = st2.getAge()-st1.getAge();
if(num == 0)
{
returnst2.getName().compareTo(st1.getName());
}
returnnum;
}
}