java集合框架TreeSet的使用 -使用说明 -实现接口 TreeSet是集合Collection的子类接口Set的实现类,是无序不重复的,但是其输出的结果是有序的,可以实现两种排序方式: 1.自然排序 2.自定义排序
TreeSet set = new TreeSet ( ) ;
set. add ( "2" ) ;
set. add ( "1" ) ;
set. add ( "4" ) ;
set. add ( "8" ) ;
set. add ( "6" ) ;
set. add ( "3" ) ;
System. out. println ( set) ;
结果: { 1 , 2 , 3 , 4 , 6 , 8 }
Com com = new Com ( ) ;
TreeSet set = new TreeSet ( com) ;
class Com implements Comparator {
@Override
public int compare ( Object o1, Object o2) {
Clea number = ( Clea) o1;
Clea number1 = ( Clea) o2;
if ( number1. age == number. age) {
return 0 ;
}
if ( number1. age > number. age) {
return 1 ;
}
if ( number1. age < number. age) {
return - 1 ;
}
return 0 ;
}
@Override
public String toString ( ) {
return super . toString ( ) ;
}
}
class Clea {
int age;
public Clea ( int age) {
this . age = age;
}
@Override
public String toString ( ) {
return "[" + age + "]" ;
}
}
java集合框架HashSet的使用 -使用说明: 重复元素的判断机制 –只要 obj == obj1 认为obj 和obj1是相同的元素 –equals与hashCode同时相等的时候,认为相同元素 (HashSet基于HashMap实现的) (利用了Hash键不能重复的特点)
import java. io. Serializable;
import java. util. HashMap;
import java. util. HashSet;
public class Test02 {
HashSet set = new HashSet ( ) ;
Person p = new Person ( ) ;
p. name = "张三" ;
p. age = 15 ;
Person p3 = new Person ( ) ;
p3. name = "张三" ;
p3. age = 15 ;
System. out. println ( p. equals ( p3) ) ;
set. add ( p) ;
set. add ( p3) ;
System. out. println ( set) ;
}
}
class Person implements Comparable {
String name;
int age;
@Override
public String toString ( ) {
return "name = " + this . name + "age =" + this . age;
}
@Override
public boolean equals ( Object obj) {
if ( ! ( obj instanceof Person ) ) {
return false ;
}
if ( ( ( Person) obj) . name. equals ( this . name) ) {
return true ;
}
return false ;
}
@Override
public int hashCode ( ) {
return this . name. hashCode ( ) ;
}
@Override
public int compareTo ( Object o) {
if ( o instanceof Person ) {
Person p = ( Person) o;
if ( this . age > p. age) {
return 1 ;
} else if ( this . age == p. age) {
return 0 ;
} else {
return - 1 ;
}
}
return 0 ;
}
}