對集合的一點總結。
對HashSet集合排序可以把它轉換成TreeSet和List的實現類ArrayList、LinkedList。
其中TreeSet實現自定義類排序需要實現Comparable接口,覆蓋comparaTo()來進行排序,也可以實現Comparator接口,覆蓋compare方法。將Comparator接口的對象作爲參數傳遞給TreeSet集合的構造器。
List實現類是ArrayList和LinkedList利用Collections類裏的sort()方法升序,reverse()方法逆序,需要自定義排序也需要實現Comparable接口,覆蓋comparaTo()來進行排序。
對集合的Set、List、Map接口的實現類remove()方法是判斷equals()是否爲true,需要重寫equals()方法時要重寫hashCode()方法,重寫最好加上@Override,不然一不小心就寫成另一個方法了。
對於HashMap遍歷的四種方法
public static void main(String[] args){
Map<String,String>map = new HashMap<String,String>();
map.put("1",value1"");
map.put("2","value2");
map.put("3","vlaue3");
//第一種:普遍使用,二次取值
System.out.println("通過Map.keySet遍歷key和value:");
for(String key:map.key.Set()){
System.out.println("key="+key+"and value="+map.get(key));
}
//第二種
System.out.println("通過Map.entrySet使用iterator遍歷key和value:");
Iterator<Map.Entry<String,String>> it = map.entrySet().iterator();
while(it.hasNext()){
Map.Entry<String,String>entry = it.next();
System.out.println("key"+entry.getKey()+"and value="+entry.getValue());
}
//第三種:
System.out.println("通過Map.entrySet遍歷key和value");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
//第四種
System.out.println("通過Map.values()遍歷所有的value,但不能遍歷key");
for (String v : map.values()) {
System.out.println("value= " + v);
}
}