Java爬坑 -- 判断两个数组是否存在相同元素 (内牛满面)
问题:判断两个数组是否存在相同元素
今天做一个数组添加操作,,但是要判断数据是否重复,,,头脑第一个想法就是遍历两个数组查询是否有重复,
然后就吧啦吧啦.....一通狂敲,如下:
1 boolean has = false; 2 String[] strOne= {"c","b","a","d"}; 3 String[] strTwo= {"a","b","d","g"}; 4 for (int i = 0; i < strOne.length; i++) { 5 if (ArrayUtils.contains(strTwo, strOne[i])) { 6 has = true; 7 break; 8 } 9 } 10 11 System.out.println(has ) 12 13
写完之后莫名的不爽,我要到循环里面进行判断..........
然后在分析问题 ,判断两个数组是否存在相同元素 .........咦------倒吸一口冷气,这丫的不就是求交集么
交集的函数不就是retainAll
然后马上开始吧啦吧啦.......一通狂敲,如下:
1 boolean has = false; 2 String[] strOne= {"c","b","a","d"}; 3 String[] strTwo= {"a","b","d","g"}; 4 HashSet<String> set = new HashSet<>(Arrays.asList(strOne)); 5 set.retainAll(Arrays.asList(strTwo)); 6 if(set.size() > 0){ 7 has = true; 8 }
虽然一个九行一个八行 ,, 但是需要我们好好想一下,,,如果问题再复杂一下呢?
一.条条大路通罗马,,,分析问题,,,找到最优
二.一些基础函数不用难免忘记