TreeSet:如果要对对象进行排序,对象类要实现Comparable接口!
TreeMap:如果要对对象进行排序,对象类要实现Comparable接口!
下面是我自己写的小程序主要传输对象
public class News implements Comparable<News>{ //news为传递的对象类
String title;
String content;
public News(String title, String content) {//构造带参函数
super();
this.title = title;
this.content = content;
}
public News() {无参函数
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传递主函数里的
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()){ //调用treemap的两个方法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的传递对象主函数里的
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);