I am at the end of my rope trying to figure this one out. Unfortunately, the only resource I have is a book, and I am simply not "getting it." The idea here is very simple. I want to pass two arrays containing objects of type comparable into the method findCommonElements. The, I want to find the objects that are similar. Finally, I want to store those values into an empty array, so that I can print this new array, which should contain all the common elements. I know I can't compare a single array index with a comparable object. I've stepped away from this several times. I even drew up a UML diagram. So if someone could show me what in the world it is I am doing wrong, I might actually continue trying to learn this stuff.
Output:
The following elements were common among all arrays:
[Ljava.lang.Integer;@c21495
Additionally, there were a total of 2 comparisons made between the arrays.
public class Test {
public static void main(String[] args) {
Integer[] coll_1 = {1, 2, 4, 6, 10, 12, 13, 14, 15, 20};
Integer[] coll_2 = {4, 6, 8, 9, 10, 11, 15, 19, 21, 23};
Object[] collections = new Object[2];
collections[0] = coll_1;
collections[1] = coll_2;
CommonElements.findCommonElements(collections);
}
}
public class CommonElements implements Comparable<Integer>{
private static int comparisons = 0;
private static Integer[] common = {};
public int getComparisons() {
return comparisons;
}
public static Comparable[] findCommonElements(Object[] collections)
{
Integer[] query = {1, 2, 3, 4, 9, 20, 21, 30, 31, 35 };
int i;
for( i = 0; i < collections.length; i++ ){
comparisons++;
if(query.equals( collections[i] )) {
common = (Integer[]) collections[i];
}
}
System.out.println("The following elements were common among all arrays: " + "\n");
System.out.println( common);
System.out.println("\n" + "Additionally, there were a total of " + comparisons + " comparisons made between the arrays." + "\n");
return common;
}
public int compareTo(Integer collections) {
return 0;
}
}
Output:
The following elements were common among all arrays:
[Ljava.lang.Integer;@c21495
Additionally, there were a total of 2 comparisons made between the arrays.