Set输出有序结果

通过TreeSet类来实现,其中Student类参实现参考之前的文章《Java集合类之Set》

	public static void treeSetStringTest(){
		
		 Set set = new TreeSet();
		 
		 set.add("a");
	     set.add("b");
	     set.add("c");
	     set.add("d");
	     set.add("e");  
	     set.add("A");
	     
	     System.out.println("-------treeset 输出有序结果---------");  
	     
	     for(String value : set){  
	            System.out.print(value+" ");  
	     } 
	     
	     System.out.println();  
	}
	
	public static void treeSetObjectTest(){
		
		 Set set = new TreeSet();
		 
		 set.add(6);
	     set.add(3);
	     set.add(2);
	     set.add(1);
	     set.add(4);  
	     set.add(5);
	     
	     System.out.println("-------treeset 输出有序结果---------");  
	     
	     for(Integer value : set){  
	            System.out.print(value+" ");  
	     } 
	     
	     System.out.println();  
	}
	
	public static void treeSetStudentTest(){
		
		 @SuppressWarnings("unchecked")
		Set set = new TreeSet(new MyComparator());
		 
		 set.add(new Student("lili",18));
		 // set.add(null);
	     set.add(new Student("jim",17));
	     set.add(new Student("green",19));
	     set.add(new Student("brown",20));
	     set.add(new Student("jack",16));  
	     set.add(new Student("ocean",15));
	     
	     System.out.println("-------treeset 输出有序结果---------");  
	     
	     for(Student value : set){  
	            System.out.print(value.getName()+"-"+value.getAge() +" ");  
	     } 
	     
	     System.out.println();  
	}

输出结果:

-------treeset 输出有序结果---------
A a b c d e 
-------treeset 输出有序结果---------
1 2 3 4 5 6 
-------treeset 输出有序结果---------
ocean-15 jack-16 jim-17 lili-18 green-19 brown-20 



你可能感兴趣的:(JAVA)