HashMapTest.java.
package com.collection;
import java.util.HashMap;
public class HashMapTest {
public static void main(String[] args) {
HashMap<String,Double> map =new HashMap();
map.put("yuwen", 90.0);
map.put("shuxue", 90.0);
map.put("yingyu", 90.0);
System.out.println(map.size());
System.out.println(map);
}
}
HashMapTest2.java
package com.collection;
import java.util.HashMap;
class Orage{
private String color;
private double weight;
public Orage(String color,double weight){
this.color = color;
this.weight = weight;
}
@Override
public String toString(){
return "Orage[color= "
+this.color+"weight="+this.weight+"]";
}
//以下两个方法是必须要重写的
@Override
public boolean equals(Object obj){
if(this == obj)
return true;
if(obj!=null && obj.getClass() == Orage.class){
Orage orage = (Orage)obj;
return this.color.equals(orage.color) &&
this.weight==orage.weight;
}
return false;
}
@Override
public int hashCode(){
return color.hashCode()+13*(int)weight;
}
}
public class HashMapTest2 {
public static void main(String[] args) {
//HashSet要求元素正确重写hashCode和equals方法
//HashMap要求key正确重写hashCode和equals方法
HashMap<Orage,Double> map =new HashMap();
map.put(new Orage("hongse",3.5),90.0);
map.put(new Orage("hongse",3.5),90.0);
map.put(new Orage("lanse",3.5),90.0);
map.put(new Orage("hongse",2.5),90.0);
System.out.println(map.size());
//用HashMap添加的元素存放不是按照添加顺序,
//所以打印出来也不是添加书序,而是存储顺序
//如果希望记住添加顺序,就应该用LinkedHashMap
System.out.println(map);
}
}
LinkedHashMapTest.java
package com.collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
public class LinkedHashMapTest {
public static void main(String[] args) {
//LinkedHashSet要求元素正确重写hashCode和equals方法
//LinkedHashMap要求key正确重写hashCode和equals方法
LinkedHashMap<Orage,Double> map =new LinkedHashMap();
map.put(new Orage("hongse",3.5),90.0);
map.put(new Orage("hongse",3.5),90.0);
map.put(new Orage("lanse",3.5),90.0);
map.put(new Orage("hongse",2.5),90.0);
System.out.println(map.size());
//用HashMap添加的元素存放不是按照添加顺序,
//所以打印出来也不是添加书序,而是存储顺序
//如果希望记住添加顺序,就应该用LinkedHashMap
System.out.println(map);
}
}
TreeMapTest.java
package com.collection;
import java.util.Comparator;
import java.util.TreeMap;
public class TreeMapTest {
public static void main(String[] args) {
//如果创建TreeMap时,没有用comparator,说明是按照自然排序
//因为String已经实现了comparator接口
//TreeMap<String,Double> score = new TreeMap();
//此处是定制排序(根据自己的需求排序),重写Comparator接口
TreeMap<String,Double> score = new TreeMap<String,Double>(new Comparator<String>(){
@Override
public int compare(String o1, String o2) {
//假定让字符串长的大于字符串短的
return o1.length()>o2.length()?
1:o1.length()<o2.length()?-1:0;
}
});
score.put("zhangsan", 20.0);
score.put("abc", 10.1);
score.put("abde", 10.1);
score.put("lisie", 10.1);
System.out.println(score.size());
System.out.println(score);
}
}