如何使用HashSet查找两个Comparable数组中的公共元素?

时间:2016-02-18 21:29:45

标签: java arrays hashset comparable

编辑:方法签名

    public Comparable[][] findCommonElements(Comparable[][] collections)

错了。它应该是

    public Comparable[] findCommonElements(Comparable[][] collections)

但是在我的IDE中更改它会让一切都变得混乱。我几乎觉得自己已经超出了我的知识范围,因为我不完全理解套装,2D阵列让我很糟糕。

我需要编写一个算法,该算法采用两个可比较数组,以线性时间效率迭代它们,并显示公共元素。 我已经读过使用HashSet会给我最快的时间效率,但我已陷入僵局。这就是原因:

我们得到了说明和一行代码,这是方法签名

public Comparable[][] findCommonElements(Comparable[][] collections)

这意味着我必须返回2d数组,"集合。"我通过电子邮件发送了我的教授使用HashSets,除了我遇到这个问题外,我获得了批准:

"您可以在findCommonElements方法中使用HashSet,但是您需要能够计算执行的比较次数。尽管散列通常非常有效,但是在发生碰撞时会进行一些比较。为此,您需要访问您使用的HashSet的源代码。你还需要一个" getComparisons()"您的CommonElements类中的方法返回比较次数。"

在两个学期的编程中,我没有学习HashSets,Maps,Tables等。我正在尝试自己学习,我并不完全理解碰撞。

我的代码确实占用了两个数组并返回了公共元素,但是我的返回语句很复杂,因为我基本上编写它以便编译(2d Comparable数组是参数)。

我是否在正确的道路上?这是代码:

public class CommonElements {

    static Comparable[] collection1 = {"A", "B", "C", "D", "E"}; //first array
    static Comparable[] collection2 = {"A", "B", "C", "D", "E", "F", "G"}; //second array
    static Comparable[][] collections = {collection1, collection2}; //array to store common elements. 
    static Set<Comparable> commonStuff = new HashSet<>(); //instance of Set containing common elements

    public static void main(String[] args) {

        CommonElements commonElements = new CommonElements(); //create instance of class CommonElements
        commonElements.findCommonElements(collections); //call the find method

    }
    public Comparable[][] findCommonElements(Comparable[][] collections) {

        Set<Comparable> addSet = new HashSet<>(); //instance of Set to add elements to

        for (Comparable x : collection1) { //adding elements from first array to my addSet
            addSet.add(x);
        }
        for (Comparable x : collection2) {
            if (addSet.contains(x)) {
            commonStuff.add(x); //checking for common elements, add to commonStuff Set
            }
        }
        System.out.println(toString(commonStuff)); //print the toString method

        return collections; //return statement, otherwise Java will whine at me
    }
    public String toString(Set<Comparable> commonStuff) { //this method gets rid of the brackets
        String elements = commonStuff.toString(); //make a String and assign it to the Set
        elements = elements.replaceAll("\\[", "").replaceAll("\\]", ""); //replace both brackets with empty space

        return "Common Elements: " + elements; //return the Set as a new String
    }
}

2 个答案:

答案 0 :(得分:1)

HashSet.add(E e)如果无法将e添加到Set,则返回false,因此我们可以说:

if (addSet.add(x)){
    //the collection did not contain x already
} else {
    //the collection contained x
}

所以你能做的就是这样:

public Comparable[] findCommonElements(){
    Set<Comparable> collectionSet1 = new HashSet<>(Arrays.asList(collection1));
    Set<Comparable> collectionSet2 = new HashSet<>(Arrays.asList(collection2));
    for (Comparable x : collectionSet1){
        if (!collectionSet2.add(x)){
            commonStuff.add(x);
        }
    }
    return commonStuff.toArray(); //convert HashSet to an array
}

请注意,您需要import java.util.Arrays;

答案 1 :(得分:1)

编辑我忘了提到我导入了Apache Commons Array Utils。非常有用。

我明白了。感谢你的帮助。我有一个main方法,它调用类的实例3次,和3个测试方法,但那些是无关紧要的。这就是给我带来麻烦的东西,现在它起作用了。 : - )

public int getComparisons() {
        return comparisons;
    } //method to return number of comparisons
    public static Comparable[] findCommonElements(Comparable[][] collections) {
        /*
        I LEARNED THAT WE HAD TO USE MORE THAN TWO ARRAYS, SO IT WAS BACK
        TO THE DRAWING BOARD FOR ME. I FIGURED IT OUT, THOUGH.
        */
        Comparable[] arr1 = collections[0]; //set initial values to 1 Dimensional arrays so the test methods can read their respective values
        Comparable[] arr2 = collections[1];
        Comparable[] arr3 = collections[2];

        /*
        THE FOLLOWING BLOCK OF CODE TAKES ALL THE PERMUTATIONS OF THE 3 ARRAYS (i.e. 1,2,3; 1,3,2; 2,1,3, etc),
        DETERMINES WHICH ARRAY IS THE SHORTEST, AND ADDS THE LONGER TWO ARRAYS TO A QUERY ARRAY.
         */
        if(arr1.length < arr2.length && arr1.length < arr3.length || arr2.length <= arr3.length) { //shortest array will become hash array. the other two will become a combined query array.
            hashArray = arr1;  //these will be utilized below to put into Sets
            queryArray = ArrayUtils.addAll(arr2, arr3);
        }
        else if(arr2.length < arr1.length && arr2.length < arr3.length || arr1.length <= arr3.length) {
            hashArray = arr2;
            queryArray = ArrayUtils.addAll(arr1, arr3);
        }
        else if(arr3.length < arr1.length && arr3.length < arr2.length || arr1.length <= arr2.length) {
            hashArray = arr3;
            queryArray = ArrayUtils.addAll(arr1, arr2);
        }
        HashSet<Comparable> intersectionSet = new HashSet<>(); //initialize Sets
        HashSet<Comparable> arrayToHash = new HashSet<>();
        for(Comparable element : hashArray) { //add shorter array to hashedArray Set
            arrayToHash.add(element);
        }
        //NOTE FROM THE JAVADOC ON THE IMPLEMENTATION OF .contains() USING HASHSET COMPARISONS
        /**
         * <p>This class offers constant time performance for the basic operations
         * (<tt>add</tt>, <tt>remove</tt>, <tt>contains</tt> and <tt>size</tt>),
         * assuming the hash function disperses the elements properly among the
         * buckets.
         */
        for(Comparable element : queryArray) {
            if(element != null) {
                comparisons++; // increment comparisons with each search
            }
            if(arrayToHash.contains(element)) { //search for matches and add to intersectionSet (.contains uses the equals method to determine if an object is within array)
                intersectionSet.add(element);
            }
        }
        return intersectionSet.toArray(new Comparable[0]); //return Set as Array defined in method signature
    }