TreeMap and TreeSet

Source: Internet
Author: User
Tags comparable

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.