import java.util.TreeSet;
/**
* 某跨境电商笔试题第一道选择题,问输出的结果
* A.Tea
* B.Coffee
* C.Coffee,Tea
* D.Compilatioin fails.
* E.The code runs with no output.
* F.An exception is thrown at runtime.
*
* 正确的答案:B
* 解析:本题因重写的比较方法始终返回0即相等,所以只会存第一个元素,后边的元素都视为与第一个相等不会被set进去
*/
public class Drink implements Comparable {
public String name;
public int compareTo(Object o) {
return 0;
}
public static void main(String[] args) {
Drink one = new Drink();
Drink two = new Drink();
one.name = "Coffee";
two.name = "Tea";
TreeSet set = new TreeSet<>();
set.add(one);
set.add(two);
System.out.println(set);
}
}
/**
* 拓展:TreeSet的特点是 有序不可重复
* Java实现对象排序的方式有两种:
* a、自然排序:java.lang.Comparable
* b、定制排序:java.util.Comparator
* 详情可参考:https://blog.csdn.net/qq_38308340/article/details/134489823?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22134489823%22%2C%22source%22%3A%22qq_38308340%22%7D
*/
2023java线下笔试题之treeSet的考查
于 2023-11-19 14:18:30 首次发布