public static Set getSameNumber(Object[] m, Object[] n) { HashSet result = new HashSet(); List list = Arrays.asList(m); for (int i = 0; i < n.length; i++) { if (list.contains(n[i])) { result.add(n[i]); } } return result; } public static void main(String[] args) { Integer[] m ={ 1, 45, 123, 55, 11, 1, 4234, 2, 223 }; Integer[] n ={ 2, 415, 123, 55, 11, 4, 2, 33, 2 }; Set set = getSameNumber(m, n); System.out.println(set); } } 输出结果:[2, 55, 11, 123]
建立一个新HashSet,先把M全放进去。然后用add()方法把N的元素一个一个放进去,判断为FALSE就放入结果集
import java.util.HashSet;
import java.util.List;
import java.util.Set;public class NumberTest {
public static Set getSameNumber(Object[] m, Object[] n) {
HashSet result = new HashSet();
List list = Arrays.asList(m);
for (int i = 0; i < n.length; i++) {
if (list.contains(n[i])) {
result.add(n[i]);
}
}
return result;
} public static void main(String[] args) {
Integer[] m ={ 1, 45, 123, 55, 11, 1, 4234, 2, 223 };
Integer[] n ={ 2, 415, 123, 55, 11, 4, 2, 33, 2 };
Set set = getSameNumber(m, n);
System.out.println(set);
}
}
输出结果:[2, 55, 11, 123]