先定义一个Person类然后创建6个单元测试方法
import java.util.Objects;
public class Person {
String name;
int age;
@Override
public boolean equals(Object o) {
System.out.println("Person equals()...");
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age && Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
下面为单元测试
import org.junit.Test;
import java.util.*;
public class MapTest {
@Test
public void test1(){
Map map=new HashMap();
map.put("Tom",23);
map.put(34,"AA");
map.put("CC",new Date());
map.put(null,null);
System.out.println(map);
}
@Test
public void test2(){
Map map=new Hashtable();
// map.put(null,123); 报错
// map.put("AA",null); 报错
System.out.println(map);
}
@Test
public void test3(){
LinkedHashMap map = new LinkedHashMap(); //开发中,对于频繁的遍历操作,建议使用此类
map.put("Tom",23);
map.put(34,"AA");
map.put("CC",new Date());
System.out.println(map);
}
@Test
public void test4(){
HashMap map=new HashMap();
map.put("AA",56);
map.put(67,"Tom");
map.put("BB",78);
map.put(new Person("Jerry",12),56);
System.out.println(map);
System.out.println(map.size());
Object value = map.remove("AA");
System.out.println(value);
System.out.println(map);
//修改
Object oldValue = map.put("BB", 99);
System.out.println(oldValue); //78
System.out.println(map);
Object value1=map.get(67);
System.out.println(value1);
}
//map的遍历
@Test
public void test5(){
HashMap map=new HashMap();
map.put("AA",56);
map.put(67,"Tom");
map.put("BB",78);
map.put(new Person("Jerry",12),56);
Set keySet = map.keySet();
//遍历
Iterator iterator = keySet.iterator();
while(iterator.hasNext())
{
Object key = iterator.next();
System.out.println(key);
}
//遍历value Collection values();
Collection values = map.values();
//使用增强for
for(Object obj:values){
System.out.println(obj);
}
}
//遍历entry集 Set entrySet()
@Test
public void test6(){
HashMap map=new HashMap();
map.put("AA",56);
map.put(67,"Tom");
map.put("BB",78);
map.put(new Person("Jerry",12),56);
//方式一 遍历entry集 Set entrySet() (推荐)
Set entrySet = map.entrySet();
Iterator iterator = entrySet.iterator();
while(iterator.hasNext())
{
Map.Entry entry= (Map.Entry) iterator.next(); //强转 内部类的应用
System.out.println(entry.getKey()+"--->"+entry.getValue());
}
//方式二:遍历entry集 keySet(),get(key)
// Set keySet = map.keySet();
// for(Object key:keySet){
// System.out.println(key+"--->"+map.get(key));
// }
}
}