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()对象来进行降序排序

TreeSet怎样排序举个例子

原文地址: https://www.cveoy.top/t/topic/fnft 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录