用java编写 在两个数组里面 找出相同的元素 并输出
来源:百度知道 编辑:UC知道 时间:2024/06/06 04:53:15
a[][]={{1,4,5,7},{2,3,4,6}}
b[][]={{7,9,10}{6,9,7}{5,1,3}}
有两个数组,需要找出这两个数组之间相同的元素。
package cn.luxh.jpa.test;import java.util.HashSet;import java.util.Set;import org.junit.Test;public class ArrayTest {
/**
* 找出两个数组中相同的元素
* @param array1
* @param array2
* @return 返回相同的元素
*/
public Set<Integer> findSameElementIn2Arrays(Integer[] array1,Integer[] array2) {
Set<Integer> sameElementSet = new HashSet<Integer>();//用来存放两个数组中相同的元素
Set<Integer> tempSet = new HashSet<Integer>();//用来存放数组1中的元素(广州达内)
for(int i=0;i<array1.length;i++) {
tempSet.add(array1[i]);//把数组1中的元素放到Set中,可以去除重复的元素
}
for(int j=0;j<array2.length;j++) {
//把数组2中的元素添加到tempSet中
//如果tempSet中已存在相同的元素,则tempSet.add(array2[j])返回false
if(!tempSe