我想將三個數組合併成一個數組。只保留共同的元素。這不是一個重複的問題。我知道還有其他的例子在線,但那是使用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甘地謝謝。 –