带有交集和联合的链表

时间:2013-11-12 01:07:07

标签: java list linked-list intersection

我有两个列表都添加了整数。我想要将两个列表和联合相交。我有我的代码,但由于某种原因它不会编译。

为什么我不能简单LinkedList.intersection(argument, argument)提出任何建议?

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;

public class IntegerSet 
{


    public static void main(String args[]) {


        LinkedList<Double> list1 = new LinkedList<Double>();
        list1.add((double) 5);
        list1.add((double) 15);
        list1.add((double) 3);
        list1.add((double) 15);


        LinkedList<Double> list2 = new LinkedList<Double>();
        list2.add((double) 15);
        list2.add((double) 8);
        list2.add((double) 16);
        list2.add((double) 11);

        // Calculating Intersection of two Set in Java
        LinkedList<Double> intersection = LinkedList.intersection(list1, list2);
        System.out.printf("Intersection of two Set %s and %s in Java is %s %n",
                list1.toString(), list2.toString(), intersection.toString());
        System.err.println("Number of elements common in two Set : "
                           + intersection.size());

        // Calculating Union of two Set in Java
        LinkedList<Double> union = LinkedList.union(list1, list2);
        System.out.printf("Union of two Set %s and %s in Java is %s %n",
                list1.toString(), list2.toString(), union.toString());
        System.out.println("total number of element in union of two Set is : "
                            + union.size());
    }

}

1 个答案:

答案 0 :(得分:1)

除了在intersection上尝试使用unionlinked list方法这是您在复杂性方面可以做的最糟糕的事情之一。另外,

// Calculating Union of two Set in Java
LinkedList<Double> union = LinkedList.union(list1, list2);

SetList不同。此外,这存在于API

col.retainAll(otherCol) // for intersection
col.addAll(otherCol) // for union

另见帖子:Intersection and union of ArrayLists in Java

第三方图书馆:Apache Commons CollectionUtils