功能概述:
添加功能
V put(K key,V value):添加元素。这个其实还有另一个功能——替换
如果键是第一次存储,就直接存储元素,返回null
如果键不是第一次存在,就用值把以前的值替换掉,返回以前的值
删除功能
void clear():移除所有的键值对元素
V remove(Object key):根据键删除键值对元素,并把值返回
判断功能
boolean containsKey(Object key):判断集合是否包含指定的键
boolean containsValue(Object value):判断集合是否包含指定的值
boolean isEmpty():判断集合是否为空
获取功能
Set<Map.Entry<K,V>> entrySet(): 返回一个键值对的Set集合
V get(Object key):根据键获取值
Set keySet():获取集合中所有键的集合
Collection values():获取集合中所有值的集合
长度功能
int size():返回集合中的键值对的对数
集合遍历
1.键找值
键找值思路:
获取所有键的集合
遍历键的集合,获取到每一个键
根据键找值
2.键值对对象找键找值
键值对对象找键和值思路:
获取所有键值对对象的集合
遍历键值对对象的集合,获取到每一个键值对对象
根据键值对对象找键和值
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int compareTo(Student s) {
int num = this.getName().compareTo(s.getName());
int num2 = (num==0) ? (this.getAge() - s.getAge()) : num;
return num2;
}
}
public class HashMapTest {
public static void main(String[] args) {
HashMap<Integer, Student> hashMap = new HashMap<>();
hashMap.put(1,new Student("zhangsan",18));
hashMap.put(4,new Student("zhaoliu",19));
hashMap.put(3,new Student("lisi",18));
hashMap.put(2,new Student("wangwu",19));
hashMap.put(5,new Student("liqi",20));
//键找值
Set<Integer> integers = hashMap.keySet();
for (Integer integer : integers) {
Student s1=hashMap.get(integer);
System.out.println(integer+","+s1.getName()+","+s1.getAge());
}
System.out.println("-------------------------------------------");
//键值对,找键找值
Set<Map.Entry<Integer, Student>> entries = hashMap.entrySet();
for (Map.Entry<Integer, Student> entry : entries) {
Integer ints=entry.getKey();
Student s2=entry.getValue();
System.out.println(ints+","+s2.getName()+","+s2.getAge());
}
}
}
public class TreeMapTest {
public static void main(String[] args) {
TreeMap<Integer, Student> treeMap = new TreeMap<>();
treeMap.put(1,new Student("zhangsan",18));
treeMap.put(4,new Student("zhaoliu",19));
treeMap.put(3,new Student("lisi",18));
treeMap.put(2,new Student("wangwu",19));
treeMap.put(5,new Student("liqi",20));
//键找值
Set<Integer> integers = treeMap.keySet();
for (Integer integer : integers) {
Student s1=treeMap.get(integer);
System.out.println(integer+","+s1.getName()+","+s1.getAge());
}
System.out.println("-------------------------------------------------");
// 键值对 找键找值
Set<Map.Entry<Integer, Student>> entries = treeMap.entrySet();
for (Map.Entry<Integer, Student> entry : entries) {
Integer key = entry.getKey();
Student s2 = entry.getValue();
System.out.println(key+","+s2.getName()+","+s2.getAge());
}
}
}