正序排列:A,B,C,D,E,F
package com. shengsiyuan2;
import java. util. Iterator;
import java. util. TreeSet;
public class TreeSetTest3
{
public static void main ( String[ ] args)
{
TreeSet set = new TreeSet ( ) ;
set. add ( "C" ) ;
set. add ( "A" ) ;
set. add ( "B" ) ;
set. add ( "F" ) ;
set. add ( "E" ) ;
set. add ( "D" ) ;
for ( Iterator iter = set. iterator ( ) ; iter. hasNext ( ) ; )
{
String value = ( String) iter. next ( ) ;
System. out. println ( value) ;
}
}
}
运行结果:
! [ 在这里插入图片描述] ( https: / / img- blog. csdnimg. cn/ 20200823203152306. JPG? x- oss- process= image/ watermark, type_ZmFuZ3poZW5naGVpdGk, shadow_10, text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTgwNDQ1OQ== , size_16, color_FFFFFF, t_70#pic_center)
## 倒序排列:F, E, D, C, B, A
```java
package com. shengsiyuan2;
import java. util. Comparator;
import java. util. Iterator;
import java. util. TreeSet;
public class TreeSetTest3
{
public static void main ( String[ ] args)
{
TreeSet set = new TreeSet ( new MyComparator ( ) ) ;
set. add ( "C" ) ;
set. add ( "A" ) ;
set. add ( "B" ) ;
set. add ( "F" ) ;
set. add ( "E" ) ;
set. add ( "D" ) ;
for ( Iterator iter = set. iterator ( ) ; iter. hasNext ( ) ; )
{
String value = ( String) iter. next ( ) ;
System. out. println ( value) ;
}
}
class MyComparator implements Comparator
{
public int compare ( Object arg0 , Object arg1)
{
String s1 = ( String) arg0;
String s2 = ( String) arg1;
return s2. compareTo ( s1) ;
}
}
}