1. The case of TreeMap (treemap<student,string>)
2. Case code:
(1)Student. Java:
1 Packagecn.itcast_04;2 3 Public classStudent {4 PrivateString name;5 Private intAge ;6 7 PublicStudent () {8 Super();9 }Ten One PublicStudent (String name,intAge ) { A Super(); - This. Name =name; - This. Age =Age ; the } - - PublicString GetName () { - returnname; + } - + Public voidsetName (String name) { A This. Name =name; at } - - Public intGetage () { - returnAge ; - } - in Public voidSetage (intAge ) { - This. Age =Age ; to } +}
(2) test class TreeMapDemo2, as follows:
1 Packagecn.itcast_04;2 3 ImportJava.util.Comparator;4 ImportJava.util.Set;5 ImportJava.util.TreeMap;6 7 /*8 * treemap<student,string>9 * Key: StudentTen * Value: String One */ A Public classTreeMapDemo2 { - Public Static voidMain (string[] args) { - //To create a collection object theTreemap<student, String> TM =NewTreemap<student, string>( - NewComparator<student>() { - @Override - Public intCompare (Student s1, Student S2) { + //Main conditions - intnum = S1.getage ()-s2.getage (); + //Secondary Condition A intnum2 = num = = 0?s1.getname (). CompareTo ( at S2.getname ()): num; - returnnum2; - } - }); - - //Create student Objects inStudent S1 =NewStudent ("Koh Phangan", 30); -Student s2 =NewStudent ("Willow Xia Hui", 35); toStudent s3 =NewStudent ("Tong Pak Fu", 33); +Student S4 =NewStudent ("燕青", 32); -Student S5 =NewStudent ("Tong Pak Fu", 33); the * //Storage Elements $Tm.put (S1, "Song Dynasty");Panax NotoginsengTm.put (S2, "Yuan Dynasty"); -Tm.put (S3, "Ming Dynasty"); theTm.put (S4, "Qing Dynasty"); +Tm.put (S5, "Han Dynasty"); A the //Traverse +Set<student> set =Tm.keyset (); - for(Student key:set) { $String value =Tm.get (key); $System.out.println (Key.getname () + "---" + key.getage () + "---" -+value); - } the } -}
Run the effect as follows:
Java Basic Knowledge Enhancement Collection Framework note 60:map collection of TreeMap (treemap<student,string>) case