package com.hrf.map;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class HashMapTest {
public static void main(String[] args) {
Map map = new HashMap();
map.put("1", "张三1");
map.put("2", "张三2");
map.put("5", "张三3");
map.put("4", "张三4");
map.put("4", "张三5");
System.out.println(map);
Set set = map.entrySet();
Object[] array = set.toArray();
for (int i = 0; i < set.size(); i++) {
System.out.println(array[i]);
}
for (Object o : array) {
System.out.println(o);
}
Iterator it = set.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
Set key = map.keySet();
System.out.println(key);
Collection values = map.values();
System.out.println(values);
Iterator it1 = map.entrySet().iterator();
while(it1.hasNext()) {
Map.Entry entry = (Entry) it1.next();
System.out.println("key = "+ entry.getKey() +"\t"+"value = "+entry.getValue());
}
}
}
package com.hrf.map;
import java.util.HashMap;
import java.util.Map;
public class HashMap2Test {
public static void main(String[] args) {
Person p1 = new Person(1001);
Person p2 = new Person(1001);
Map map = new HashMap();
map.put(p1, "张三");
map.put(p2, "张三2");
System.out.println(map);
}
static class Person{
private Integer id;
public Person(Integer id) {
super();
this.id = id;
}
public Person() {
super();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public String toString() {
return "Person [id=" + id + "]";
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public boolean equals(Object obj) {
return id.equals(((Person)obj).id);
}
}
}
package com.hrf.map;
import java.util.Map;
import java.util.TreeMap;
public class TreeMapTest {
public static void main(String[] args) {
Person p1 = new Person(1001);
Person p2 = new Person(1002);
Person p3 = new Person(1003);
Map map = new TreeMap((x,y)->((Person)x).id-((Person)y).id);
map.put(p1, "张三");
map.put(p2, "张三2");
map.put(p3, "张三3");
System.out.println(map);
}
static class Person{
private Integer id;
public Person(Integer id) {
super();
this.id = id;
}
public Person() {
super();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public String toString() {
return "Person [id=" + id + "]";
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public boolean equals(Object obj) {
return id.equals(((Person)obj).id);
}
}
}