Java Array, Finding Duplicates

前端 未结 14 848
闹比i
闹比i 2020-11-22 09:13

I have an array, and am looking for duplicates.

duplicates = false;
for(j = 0; j < zipcodeList.length; j++){
    for(k = 0; k < zipcodeList.length; k++         


        
14条回答
  •  有刺的猬
    2020-11-22 09:41

    @andersoj gave a great answer, but I also want add new simple way

        private boolean checkDuplicateBySet(Integer[] zipcodeList) {
            Set zipcodeSet = new HashSet(Arrays.asList(zipcodeList));
            if (zipcodeSet.size() == zipcodeList.length) {
                return true;
            }
            return false;
        }
    

    In case zipcodeList is int[], you need convert int[] to Integer[] first(It not auto-boxing), code here

    Complete code will be:

        private boolean checkDuplicateBySet2(int[] zipcodeList) {
            Integer[] zipcodeIntegerArray = new Integer[zipcodeList.length];
            for (int i = 0; i < zipcodeList.length; i++) {
                zipcodeIntegerArray[i] = Integer.valueOf(zipcodeList[i]);
            }
    
            Set zipcodeSet = new HashSet(Arrays.asList(zipcodeIntegerArray));
            if (zipcodeSet.size() == zipcodeList.length) {
                return true;
            }
            return false;
        }
    

    Hope this helps!

提交回复
热议问题