我想将三个数组合并成一个数组。只保留共同的元素。这不是一个重复的问题。我知道还有其他的例子在线,但那是使用int [],我不知道如何用Comparable来完成。如何将常用元素合并到一个数组中?
我需要什么帮助:
如何将单个组合/更新阵列添加到二维数组。
如何计算每次元素比较的迭代次数。
如果我想如何更改我现在有一个列表的数组? - 我想也许这会更容易添加。
我是编程的新手,我将不胜感激。我想通过阅读书籍和在线搜索来学习java。
这是我到目前为止。
public class Common{
Comparable [] col_1 = {1, 1, 2};
Comparable [] col_2 = {1, 1, 2,3};
Comparable [] col_3= {1, 1, 2,3,4,};
Comparable [][] collections = {col_1, col_2, col_3};
int comparisonCount = 0
public Comparable[] findCommon(Comparable [][] collections){
int i, j, k, x, y;
for(i = 0; i< col_1.length; i++){
for(j = 0; j < col_2.length; j++){
for(k = 0; k < col_3.length; k++){
comparisonCount++;
// This should be counting but is not...
if(col_1[i].compareTo(col_2[j]) == 0 && col_1[i].compareTo(col_3[k]) ==0){
//keep searching until last element & allow duplicates & add to collections or a temp[]
}
}
}
}
// Here I'm not sure how to add the elements to the collection
for (x = 0; x < collections.length; x++){
for(y = 0; y< collections[x].length; y++){
collections [x][y] = ?????? // not sure how to add results here
}
}
}
public void setComparisons(int count){
count = comparisonCount;
}
public int getComparisons(){
return comparisonCount;
}
public class Sorting {
public static void main(String[] args) {
Common m = new Common();
//I want to test it from here but I don't know how to initialize each array.
for(int x=0; x < m.collections.length; x++){
for(int y= 0; y< m.collections[x].length; y++){
System.out.println(m.collections[x][y]);
}
// what I should be getting is only (1, 1, 2) - the order is not important really. I just want to learn.
}
System.out.println(m.getComparisons());
}
}(在简单的顺序)
@Herman甘地谢谢。 –