我认为这可能是你在找什么。请注意,如果该值存在于第二个数组中,但不在第一个数组中,它将仅添加到第三个“数组”中。在你的例子中,只有兔子会被储存,而不是狗(尽管两条狗都不存在)。这个例子可能会缩短,但我想保持这样,所以更容易看到发生了什么。
首次进口:
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