package com.yingcheng1101.collection.set.treeset;
import java.util.Comparator;
import java.util.TreeSet;
public class Set_TreeSet_1 {
public static void main(String[] args) {
// 创建一个构造函数参数是一个Comparator接口子类的类的TreeSet集合
// 该Comparator接口子类的compare()是比较两个字符串的长度
TreeSet tree = new TreeSet(new ImpComparator());
// tree添加五个长度不同的字符串
System.out.println("状态:" + tree.add("eeeee"));
System.out.println(tree);
System.out.println("状态:" + tree.add("a"));
System.out.println(tree);
System.out.println("状态:" + tree.add("ccc"));
System.out.println(tree);
System.out.println("状态:" + tree.add("bb"));
System.out.println(tree);
System.out.println("状态:" + tree.add("dddd"));
System.out.println(tree);
// 添加一个非字符串对象
tree.add(new Set_TreeSet_1());
System.out.println(tree);
}
}
// 实现Comparator接口
class ImpComparator implements Comparator {
private static int i;
public int compare(Object obj_1, Object obj_2) {
System.out.println("run:" + i++);
if (!(obj_1 instanceof String) && !(obj_2 instanceof String)) {// 判断obj_1,obj_2是否都是String,有一个不是就抛出运行时异常
throw new RuntimeException("类型错误");
}
// 返回obj_2的字符串长度与obj_1的差值
String str_1 = (String) obj_1;
String str_2 = (String) obj_2;
return str_1.length() - str_2.length();// 第一个参数是tree集合新添加元素,第二个参数是后续需要与新添加的元素比较的tree已存在的元素
// 结果为正数添加到第二个参数后面,结果为负数添加到第二个参数前面,结果为0不添加
}
}
// run:0
// 状态:true
// [eeeee]
// run:1
// 状态:true
// [a, eeeee]
// run:2
// run:3
// 状态:true
// [a, ccc, eeeee]
// run:4
// run:5
// 状态:true
// [a, bb, ccc, eeeee]
// run:6
// run:7
// 状态:true
// [a, bb, ccc, dddd, eeeee]
// run:8
// Exception in thread "main" java.lang.ClassCastException:
// com.yingcheng1101.collection.set.treeset.Set_TreeSet_1 cannot be cast to
// java.lang.String
// at
// com.yingcheng1101.collection.set.treeset.ImpComparator.compare(Set_TreeSet_1.java:45)
// at java.util.TreeMap.put(TreeMap.java:552)
// at java.util.TreeSet.add(TreeSet.java:255)
// at
// com.yingcheng1101.collection.set.treeset.Set_TreeSet_1.main(Set_TreeSet_1.java:28)
TreeSet集合根据字符串长度添加元素
最新推荐文章于 2022-10-10 03:00:00 发布