数据结构一直,用法类似:HasMap->HashSet,TreeMap->TreeSet
Map:存入键值对,同时要保证键的唯一性.
|--HashMap:采用哈希表数据结构.判断重复元素需要覆盖hashCode、equals方法,HashSet由HashMap得来.
线程不安全,可以存放null键、null值.
|--HashTable:数据结构同样是哈希表,线程安全,不可以存放null键、null值,效率低,被HashMap取代.
|--TreeMap: 采用二叉树数据结构.可以对TreeMap集合中的键进行排序.
※注意:1、区分HashMap、HashTable的区别:线程安全性不同,是否可以存放null值,效率.
2、
Map集合取出元素的原理:
先将Map转成Set集合,然后对Set集合进行迭代.
keySet:将所有的键取出放在Set集合中,在根据Set集合得到的key值取出value值.
entrySet:将键值的关系取出存入Set集合,监制关系有自己的类型,为Map接口中定
义的静态接口Map.Entry.可以通过getKey(),getValue()方法取值,
什么时候使用Map集合?
————当出现了对象之间存在映射关系时,就需要使用Map集合.
import java.util.*;
class TreeMapDemo
{
public static void main(String[] args)
{
TreeMap<Student,String> hm = new TreeMap<Student,String>(
newComparator<Student>()
{
public intcompare(Student st1, Student st2)
{
if(st1.getAge() > st2.getAge())
return1;
elseif (st1.getAge() == st2.getAge())
returnst1.getName().compareTo(st2.getName());
return-1;
}
});
hm.put(new Student("张三", 20),"北京");
hm.put(new Student("李四", 21),"西安");
hm.put(new Student("王五", 15),"重庆");
hm.put(new Student("赵六", 26),"成都");
hm.put(new Student("孙悦", 25),null); //HashMap可以存null值,而HashTable不可以,因此,不能用get方法返回null来判断键值是否存在,而应该用containsKey方法判断.
//注意:put方法有返回值,返回的是键值对应关系的值,集合中原来对键值没有指定关系,返回null,有则返回原来的值.
String a = hm.put(newStudent("小七", 12), "绵阳"); //原来集合中没有对键值(new Student("小七", 12))指定关系,返回为null
//hm.put(new Student("小七", 12),"绵阳"); //未覆盖hashCode方法和equals方法时,能够存入相同的元素.
String b = hm.put(newStudent("小七", 12), "太原"); //原来对该键值(new Student("小七",12))指定了对应关系,返回原来已经指定的值.而这里的太原覆盖了原来的绵阳.
System.out.println(a + ".." +b);
Set<Map.Entry<Student,String>> s = hm.entrySet();
for(Iterator<Map.Entry<Student,String>> it = s.iterator();it.hasNext(); )
{
Map.Entry<Student,String> me = it.next();
Student stu =me.getKey();
String addr =me.getValue();
System.out.println(stu.getName()+ ".." + stu.getAge() + ".." + addr);
}
}
}
class Student
{
private String name;
private int age;
Student(String name, int age)
{
this.name = name;
this.age =age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public int hashCode() //注意,判断HashSet、HashMap集合的唯一性,覆盖hashCode和equals方法,而TreeMap、TreeMap排序实现comparable或comparator接口.
{
return name.hashCode() +age*29;
}
public boolean equals(Object obj)
{
if (!(obj instanceofStudent))
returnfalse;
Student student =(Student)obj;
returnthis.name.equals(student.name) &&this.age == student.age;
}
public String toString()
{
return name + ".." + age;
}
}