zoukankan      html  css  js  c++  java
  • 找出两个数组中相同的元素

    import java.util.HashSet;
    import java.util.Set;
    
    import org.junit.Test;
    
    /**
     * 类描述
     * @author 赵炫
     * @create_time 2012-9-22 上午10:40:23
     * @project Hlgw
     */
    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(!tempSet.add(array2[j])) {
                  //返回false,说明当前元素是两个数组中相同的元
                  sameElementSet.add(array2[j]);
              }
          }
          return sameElementSet;
      }
      
      
      @Test
      public void testFindSameElementIn2Arrays(){
          Integer[] array1 = {1,2,3,4,1,2,4,6,7,8,10,22,33};
          Integer[] array2 = {1,2,3,4,1,2,4,6,7,8,10,22,33,55,66,77,88,99};
          Set<Integer> sameElementSet = findSameElementIn2Arrays(array1,array2);
          for(Integer i : sameElementSet) {
              System.out.println(i);
          }
      }
    }

    结果:

    1
    2
    33
    3
    4
    6
    22
    7
    8
    10

  • 相关阅读:
    jquery判断设备是否是手机
    jQuery -- touch事件之滑动判断(左右上下方向)
    sass制作雪碧图
    js时间字符串转为标准时间
    装箱和拆箱
    Dictionary泛型集合实现山寨版金山词霸
    泛型集合
    ArrayList集合与索引器及Hashtable
    黑马程序员--静态方法和静态类
    黑马程序员--多态练习(手机工厂)
  • 原文地址:https://www.cnblogs.com/xuanzai/p/2697834.html
Copyright © 2011-2022 走看看