TreeSet: If you want to sort objects, the object class implements the comparable interface!
TREEMAP: If you want to sort objects, the object class implements the comparable interface!
The following is a small program that I write myself main transfer object
public class News implements comparable<news>{//news for the passed object class
String title;
String content;
Public News (string title, string content) {//constructor with parameter function
Super ();
This.title = title;
this.content = content;
}
Public News () {No parameter function
Super ();
}
@Override
public int compareTo (News o) {
TODO auto-generated Method Stub
@SuppressWarnings ("unused")
News news = (news) o;
if (This.title.compareTo (o.title) >0) {
return 1;
}else if (This.title.compareTo (o.title) <0) {
return-1;
}else{
return 0;
}
}
}
TreeMap Pass the main function.
Treemap<string, news> treemap=new treemap<string,news> ();
Treemap.put ("3", New News ("A", "Cjjdi"));
Treemap.put ("1", New News ("D", "Cjnsdki"));
Treemap.put ("B", New News ("1", "Chuidil"));
Treemap.put ("A", New News ("4", "Cnsoai"));
Iterator Ti1=hashmap.entryset (). Iterator ();
while (Ti1.hasnext ()) {//Call TreeMap two methods Hasnext next
@SuppressWarnings ("Unchecked")
Entry<string, news> e1= (entry<string, news>) Ti1.next ();
System.out.println ("Key:" +e1.getkey () + "value:" +e1.getvalue (). Title+ "" +e1.getvalue (). content);
、
HashSet in the main function of the Transfer object.
Hashset<news> hashset2=new hashset<news> ();
News News5=new News ("G", "Cnidjdi");
News News6=new News ("B", "Cnidjdi");
News News7=new News ("P", "Cnidjdi");
Hashset2.add (NEWS5);
Hashset2.add (NEWS6);
Hashset2.add (NEWS7);
Iterator<news> It2=hashset2.iterator ();
while (It2.hasnext ()) {
News6=it2.next ();
System.out.print (News6.title);
System.out.println (news6.content);
TreeMap and TreeSet