Java TreeSet 排序:实现 Comparable 接口或使用 Comparator 对象
TreeSet 通过实现 Comparable 接口或传入 Comparator 对象来进行排序。
示例:
import java.util.*;
public class TreeSetExample {
public static void main(String[] args) {
// 实现 Comparable 接口进行排序
TreeSet<String> set1 = new TreeSet<>();
set1.add('apple');
set1.add('banana');
set1.add('orange');
System.out.println('set1: ' + set1); // set1: [apple, banana, orange]
// 传入 Comparator 对象进行排序
TreeSet<String> set2 = new TreeSet<>(Comparator.reverseOrder());
set2.add('apple');
set2.add('banana');
set2.add('orange');
System.out.println('set2: ' + set2); // set2: [orange, banana, apple]
}
}
在上面的例子中,set1 通过实现 Comparable 接口来进行默认的升序排序,set2 则通过传入 Comparator.reverseOrder() 对象来进行降序排序。
原文地址: https://www.cveoy.top/t/topic/odg4 著作权归作者所有。请勿转载和采集!