标签:public import method java 元素
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; public class SortedSetTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub //1.创建集合 SortedSet ss = new TreeSet(); //2.向集合中添加元素 ss.add(1);//自动装箱 ss.add(3); ss.add(2); ss.add(-1); //3.遍历输出 Iterator it = ss.iterator(); while(it.hasNext()){ System.out.println(it.next()); } System.out.println("========================================="); ss.clear(); //向集合中添加字符串 ss.add("nihao"); ss.add("wobuhao"); ss.add("wohenhao"); ss.add("weishenmehuizheyang?"); it = ss.iterator(); while(it.hasNext()){ System.out.println(it.next()); } System.out.println("========================================="); ss.clear(); //向集合中添加日期 String st1 = "2008-08-08"; String st2 = "2009-08-08"; String st3 = "2008-09-08"; String st4 = "2008-08-09"; String st5 = "2012-08-08"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd"); try { Date date1 =sdf.parse(st1); Date date2 =sdf.parse(st2); Date date3 =sdf.parse(st3); Date date4 =sdf.parse(st4); Date date5 =sdf.parse(st5); ss.add(date1); ss.add(date2); ss.add(date3); ss.add(date4); ss.add(date5); } catch (ParseException e) { e.printStackTrace(); } it = ss.iterator(); while(it.hasNext()){ System.out.println(it.next()); } System.out.println("=============================="); ss.clear(); //向集合中添加自定义元素 user User u1 = new User(10,"zhangdan"); User u2 = new User(20,"lisi"); User u3 = new User(5,"naliu"); ss.add(u1); ss.add(u2); ss.add(u3); it = ss.iterator(); while(it.hasNext()){ System.out.println(it.next()); } System.out.println("=============================="); } } /** * 存在的元素为什么会自动排序,因为它们实现了comprable接口,存在元素时,会调用comprareTo()方法。 */ 用户user
//User1 实现了comprable接口,或者是定义一个比较器
public class User implements Comparable{
private int age;
private String name;
public User(int age,String name){
this.age = age;
this.name = name;
}
public User(){
}
@Override
public int compareTo(Object o) {
int age1 =this.age;
int age2 = ((User)o).age;
return age1-age2;
}
public String toString(){
return "name=" + name + "age="+age;
}
}
本文出自 “gaogaozi” 博客,请务必保留此出处http://hangtiangazi.blog.51cto.com/8584103/1669870
标签:public import method java 元素
原文地址:http://hangtiangazi.blog.51cto.com/8584103/1669870