【发布时间】:2015-09-28 02:46:14
【问题描述】:
我正在尝试将三个数组合并为一个数组。只保留共同的元素。这不是一个重复的问题。我知道网上还有其他示例,但那是使用 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());
}
}
【问题讨论】:
标签: java algorithm multidimensional-array