【问题标题】:How to add ArrayList elements in TreeSet or TreeMap如何在 TreeSet 或 TreeMap 中添加 ArrayList 元素
【发布时间】:2016-02-24 21:26:38
【问题描述】:

众所周知,我们在使用TreeSet时需要实现Comparable接口并添加compareTo()。不这样做会抛出 ClassCastException。 现在我有一个 TreeSet,我需要将 ArrayLists 添加为 TreeSet 的元素。

如果我们写:

ArrayList al = new ArrayList();
ArrayList al2 = new ArrayList();
ArrayList al3 = new ArrayList();
TreeSet ts = new TreeSet();
ts.add(al);
ts.add(al2);
ts.add(al3);

它抛出 ClassCastException。

问题:如何将 ArrayList 实例(不是它们的元素)添加到 TreeSet 或 TreeMap?

【问题讨论】:

  • 你真的需要将数组列表的元素自己添加到数组列表的树集中吗?
  • ArrayList,而不是元素。我的意思是树应该理想地包含节点中的列表引用

标签: java dictionary collections set comparable


【解决方案1】:

如果您确实需要添加数组列表(作为实例)而不是其元素,您应该使用另一个构造函数而不是空的构造函数,考虑将 constructor 作为参数作为比较器。

TreeSet(Comparator<? super E> comparator)

构造一个新的空树集,根据指定的比较器排序。

您可以为您的目的预先定义一个Comparator,其中包含您对相关数组列表的实际想要的含义。

然后添加数组列表实例,它将根据您的比较器进行正确比较。


例如,您可以定义一个 Comparator,它会根据数组列表的大小比较数组列表(示例简单比较):

public class MyArrayListComparator implements java.util.Comparator<ArrayList> {

    public int compare(ArrayList al1, ArrayList al2) {
        if (al1.size() > al2.size())
            return 1;
        if (al1.size() < al2.size())
            return -1;
        return 0;
    }
}

然后在你的代码中:

    ArrayList al = new ArrayList();
    ArrayList al2 = new ArrayList();
    ArrayList al3 = new ArrayList();
    TreeSet ts = new TreeSet(new MyArrayListComparator());
    ts.add(al);
    ts.add(al2);
    ts.add(al3);

注意

TreeSet ts = new TreeSet(new MyArrayListComparator());

这实际上是一个很好的例子来说明 Comparable 和 Comparator 之间的区别:

  • Comparable 由您要使用的类实现,具有特定行为,您无法更改或添加它
  • 比较器是一个外部实现,您可以添加(如果相关消费者支持)具有您想要的行为

请查看 this SO Q/A 了解有关 Comparable 与 Comparator 的更多详细信息。

【讨论】:

    【解决方案2】:

    目前您正在添加 ArrayList 对象,而不是其中的元素。如另一个答案中所述,使用 addAll 将起作用,因为最终它将遍历每个 ArrayList 并添加各个元素。

    【讨论】:

      【解决方案3】:

      1) 如前所述,您将 ArrayList 添加到 TreeSet,而不是 ArrayList 中的元素。

      al.add(__something__);
      ts.add(al.get(__something-to-get-your-element-from-al__));
      

      2) 不建议使用原始类型,因为 Lists 和 Sets 是泛型类型:

      List<String> al = new ArrayList();
      Set<String> ts = new TreeSet();
      al.add("hello");
      al.add("hello2");
      ts.add(al.get(0));
      ts.add(al.get(1));
      

      或:

      ts.addAll(al); //which will add to your TreeSet all the elements that are in the ArrayList.
      

      编辑:3)可能您想将 ArrayList 添加到 TreeSet,然后您必须像这样声明集合:

      List<String> al = new ArrayList();
      //add elements to al
      Set<List<String>> ts = new TreeSet();
      ts.add(al);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-07
        • 2014-04-10
        • 2015-08-16
        • 1970-01-01
        • 1970-01-01
        • 2012-10-08
        • 2012-03-21
        相关资源
        最近更新 更多