TreeSet
无序,不可重复,可排序的
在TreeSet集合里的元素都会按一定的大小顺序排序
public class main {
public static void main(String[] args) {
TreeSet<customInt> ts = new TreeSet();
ts.add(new customInt(20));
ts.add( new customInt(10));
ts.add(new customInt(40));
ts.add(new customInt(30));
for (customInt t : ts) {
System.out.println(t.i);
}
}
}
class customInt{
int i ;
public customInt(int i){
this.i=i;
}
}
以上代码出现错误:
类型转换异常.
TreeSet有一个构造函数,可以传一个Comparator类型的参数
最后赋给TreeMap的comparator
TreeSet的排序规则按照comparrator(比较器)来比较排序
如果不传比较器直接走else
Comparator<? super K> cpr = comparator;
// if (cpr != null) {
// do {
// parent = t;
// cmp = cpr.compare(key, t.key);
// if (cmp < 0)
// t = t.left;
// else if (cmp > 0)
// t = t.right;
// else
// return t.setValue(value);
// } while (t != null);
// }
else {
if (key == null)//排除空值
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>) key;//把key转换成Comparartor类型
do {
parent = t;
cmp = k.compareTo(t.key);//转换就是为了进行比较
if (cmp < 0);//自平衡二叉树按左小右大原则存放
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
未实现comparable接口将会在强制类型转换的时候报错
int,String,Integer等类型都实现了Comparble接口
自定义类实现Comparable接口
自定义的customInt类实现Comparable接口
class customInt implements Comparable<customInt>{
int i ;
public customInt(int i){
this.i=i;
}
public int compareTo(customInt o) {
return this.i-o.i;//返回值小于0代表this.i小于o.i。如果返回值大于0则反之
}
}
根据实际需求重写compareTo()方法
单独编写比较器
不实现接口,单独编写比较器
比较器实现java.util.Comparator接口
(Comparator是java.util包下的,Comparable是java.lang下的)
class customInt {
int i ;
public customInt(int i){
this.i=i;
}
}
class customComparator implements Comparator<customInt>{
@Override
public int compare(customInt o1, customInt o2) {
return o1.i-o2.i;
}
}
在实例化集合的时候传入比较器
TreeSet<customInt> ts = new TreeSet(new customComparator());
同样进行比较
如果比较规则只有一个的时候,建议实现Comparable接口
如果比较规则有多个并且需要频繁切换,建议编写Comparator接口
Comparator符合OCP原则
Collections工具类
//Collections.synchronizedList(),把集合变成线程安全的
List<customInt> list = new ArrayList();
Collections.synchronizedList(list);
class customInt {
int i ;
public customInt(int i){
this.i=i;
}
}
public class main {
public static void main(String[] args) {
List<customInt> list = new ArrayList();
list.add(new customInt(6));
list.add(new customInt(2));
list.add(new customInt(4));
list.add(new customInt(9));
Collections.sort(list);
}
}
编译错误
想要对数组进行排序,一定要保证集合中的元素实现了Comprarable接口
class customInt implements Comparable<customInt>{
int i ;
public customInt(int i){
this.i=i;
}
public int compareTo(customInt o) {
return this.i-o.i;
}
}
按从小到大排序