Two kinds of extraction methods of/*map collection
* 1, KeySet ()
* 2, EntrySet ()
* */
Define a student class rewrite Equals, Hashcode three methods, implements the comparable interface and overrides the Comparato method
Package collection;
public class Student implements comparable<student>{
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.) {
This.age = age;
}
@Override
public int hashcode () {
Return This.name.hashCode () +age*39;
}
@Override
public boolean equals (Object obj) {
if (! ( obj instanceof Student))
throw new ClassCastException ("The conversion type does not match");
Student Student = (Student) obj;
Return This.name.equals (Student.getname ()) && this.age = = Student.getage ();
}
public int CompareTo (Student stu) {
int num = new Integer (this.age). CompareTo (New Integer (Stu.getage ()));
if (num = = 0)
Return This.name.compareTo (Stu.getname ());
return num;
}
@Override
Public String toString () {
return name + age;
}
}
Define a HashMap class
Import Java.util.Comparator;
Import Java.util.HashMap;
Import Java.util.Iterator;
Import Java.util.Map;
Import Java.util.Set;
public class MapTest1 {
public static void Main (string[] args) {
Hashmap<student,string> HM = new hashmap<student,string> ();//not TreeMap call not Comparato method
Hm.put (New Student ("Aisi1", 22), "Shanghai");
Hm.put (New Student ("Disi2", 24), "Shanghai");
Hm.put (New Student ("Cisi4", 21), "Shanghai");
Hm.put (New Student ("Aisi3", 25), "Shanghai");
The first method of removal keyset
set<student> KeySet = Hm.keyset ();
Iterator<student> it = Keyset.iterator ();
while (It.hasnext ()) {
Student stu = It.next ();
String address = Hm.get (stu);
System.out.println (stu+ ":" +address);
}
System.out.println ("===================");
The second method of removal entryset
Set<map.entry<student, string>> entryset = Hm.entryset ();
Iterator<map.entry<student,string>> it1 = Entryset.iterator ();
while (It1.hasnext ()) {
Map.entry<student, string> me = It1.next ();
Student stu = Me.getkey ();
String addr = Me.getvalue ();
System.out.println (stu+ ":" +addr);
}
}
}
Map of Keyset and EntrySet