我認爲這可能是你在找什麼。請注意,如果該值存在於第二個數組中,但不在第一個數組中,它將僅添加到第三個「數組」中。在你的例子中,只有兔子會被儲存,而不是狗(儘管兩條狗都不存在)。這個例子可能會縮短,但我想保持這樣,所以更容易看到發生了什麼。
首次進口:
import java.util.ArrayList;
import java.util.List;
然後執行以下操作來填充和分析陣列
String a1[] = new String[]{"cat" , "dog"}; // Initialize array1
String a2[] = new String[]{"cat" , "rabbit"}; // Initialize array2
List<String> tempList = new ArrayList<String>();
for(int i = 0; i < a2.length; i++)
{
boolean foundString = false; // To be able to track if the string was found in both arrays
for(int j = 0; j < a1.length; j++)
{
if(a1[j].equals(a2[i]))
{
foundString = true;
break; // If it exist in both arrays there is no need to look further
}
}
if(!foundString) // If the same is not found in both..
tempList.add(a2[i]); // .. add to temporary list
}
tempList現在將包含「兔」爲根據的規範。如果有必要需要它是第三個數組,你可以很簡單地做它轉換成如下:
String a3[] = tempList.toArray(new String[0]); // a3 will now contain rabbit
要打印在清單或陣列的內容做:
// Print the content of List tempList
for(int i = 0; i < tempList.size(); i++)
{
System.out.println(tempList.get(i));
}
// Print the content of Array a3
for(int i = 0; i < a3.length; i++)
{
System.out.println(a3[i]);
}
[什麼您是否嘗試過?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) –
簡單:'String result =「rabbit」;' – Maroun
更具體。 – HericDenis