如果我理解你的問題,你可以從創建contains(Integer[], Integer)
方法開始。迭代數組並返回true
如果數組包含該值。
private static boolean contains(Integer[] a, Integer v) {
for (Integer t : a) {
if (t.equals(v)) {
return true;
}
}
return false;
}
然後你可以利用它來迭代你的數組兩次。一次執行計數,第二次用count
元素數填充新創建的數組。喜歡的東西,
public static Integer[] retainAll(Integer[] a, Integer[] b) {
int count = 0;
for (Integer val : a) {
if (contains(b, val)) {
count++;
}
}
Integer[] out = new Integer[count];
count = 0;
for (Integer val : a) {
if (contains(b, val)) {
out[count++] = val;
}
}
return out;
}
然後對其進行測試,
public static void main(String[] args) {
Integer[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 200, 5, 6, 5 };
Integer[] array2 = { 12, 2, 3, 2, 200, 5 };
System.out.println(Arrays.toString(retainAll(array, array2)));
}
輸出被請求的過程
[2, 3, 5, 200, 5, 5]
,你也可以使用Arrays.asList(T...)
和retainAll()
像
public static Integer[] retainAll(Integer[] a, Integer[] b) {
List<Integer> al = new ArrayList<>(Arrays.asList(a));
al.retainAll(Arrays.asList(b));
return al.toArray(new Integer[al.size()]);
}
你會怎麼做_conceptually_? – 2014-10-06 01:28:02
_「我不知道如何編碼我試圖做的事情」 - 花點時間在代碼之外思考它,然後拿出代碼來匹配你的想法。因爲它聽起來有點像家庭作業問題... – Krease 2014-10-06 01:35:53
可能的[兩個列表中的通用元素]的重複(http://stackoverflow.com/questions/5943330/common-elements-in-two-lists) – 2014-10-06 01:40:44