HashMap
*HashMap集合本身基于哈希表
* 它可以保证键的唯一性(Map都是针对键有效),对象作为键要保证重写了equals()方法
* HashMap<Student,String>
例子:
public static void main(String[] args) {
HashMap<Student,String> map = new HashMap<Student,String>();
Student s1 = new Student("西施", 27) ;
Student s2 = new Student("杨贵妃", 35) ;
Student s3 = new Student("王昭君", 30) ;
Student s4 = new Student("貂蝉",28) ;
Student s5 = new Student("西施", 27) ;
//添加元素
map.put(s1, "元朝") ;
map.put(s2, "宋朝") ;
map.put(s3, "唐朝") ;
map.put(s4, "清朝") ;
map.put(s5, "金") ;
Set<Student> set = map.keySet();
for(Student s : set) {
String value = map.get(s);
System.out.println(s.getName()+"---"+s.getAge()+"---"+value);
}
}
结果:
杨贵妃---35---宋朝
王昭君---30---唐朝
西施---27---金
貂蝉---28---清朝
LinkedList
*LinkedHashMap<K,V> :是Map接口基于哈希表和链接列表实现的
*哈希表保证键的唯一性
*链接列表保证元素有序性(存储和取出一致)
例子:
public static void main(String[] args) {
LinkedHashMap<String, String> map = new LinkedHashMap<String,String>() ;
//添加元素
map.put("it001", "hello");
map.put("it002", "mysql");
map.put("it003", "world");
map.put("it004", "javaweb");
map.put("it001", "javaee");
Set<String> set = map.keySet() ;
for(String key :set) {
String value = map.get(key) ;
System.out.println(key+"----"+value);
}
}
结果:
it001----javaee
it002----mysql
it003----world
it004----javaweb
TreeMap
*TreeMap基于红黑树结构的Map接口的实现
数据按一定的规则进行排序存储,自定义类作为键有两种排序方法:
1)自然排序(自定义类实现Comparable接口并且重写其中的compareTo方法
2)比较器排序,Comparator 重写compare方法
实例:
public static void main(String[] args) {
//创建一个TreeMap集合,使用比较器排序的方式
//匿名内部类的方式
TreeMap<Student, String> tm = new TreeMap<Student,String>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
//主要条件:年龄从小到大
int num =s1.getAge() -s2.getAge() ;
//年龄相同,不一定姓名一样
int num2 = num ==0 ? s1.getName().compareTo(s2.getName()): num ;
return num2 ;
}
} );
//创建学生对象
Student s1 = new Student("唐伯虎", 28) ;
Student s2 = new Student("杜甫", 35) ;
Student s3 = new Student("李白", 40) ;
Student s4 = new Student("李清照", 32) ;
Student s5 = new Student("唐伯虎", 28) ;
Student s6 = new Student("苏轼", 35) ;
//添加到集合中
tm.put(s1, "宋代") ;
tm.put(s2, "唐代") ;
tm.put(s3, "唐代") ;
tm.put(s4, "宋代") ;
tm.put(s5, "清代") ;
tm.put(s6, "清代") ;
//遍历
Set<Student> set = tm.keySet() ;
for(Student key :set) {
String value = tm.get(key) ;
System.out.println(key.getName()+"---"+key.getAge()+"---"+value);
}
}
结果:
唐伯虎---28---清代
李清照---32---宋代
杜甫---35---唐代
苏轼---35---清代
李白---40---唐代
Hashtable
* HashMap集合和Hashtable的区别?
* 共同点:都是map接口的实现类,都是基于哈希表的实现类
* Has