题目:找出两个数组(有重)相同的元素,两种方法
public class 出两个数组相同的元素 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] test1 = {"damon","happy","ly","good","losers"};
String[] test2 = {"love","winner","damon","mai"};
//*********************************方法1*******************************
//两两比较
for (int i = 0; i < test1.length; i++) {
for (int j = 0; j < test2.length; j++) {
if(test1[i].equals(test2[j])){
System.out.println((test2[j]));
}
}
}
//*********************************方法2*******************************
HashSet<String> hs = new HashSet<String>();
//先把test1的元素放到HashSet(相同的只放一次)
for (int i = 0; i < test1.length; i++) {
if(!hs.contains(test1[i])){
hs.add(test1[i]);
}
}
//用HashSet判断test2的元素是否有重复
for (int j = 0; j < test2.length; j++) {
if(hs.contains(test2[j])){
System.out.println((test2[j]));
}
}
}
----------------------------------我是优美的分割线----------------------------------