Home  >  Article  >  Java  >  Java determines whether array elements are repeated

Java determines whether array elements are repeated

尚
Original
2019-11-22 13:17:278422browse

Java determines whether array elements are repeated

java determines whether the array elements are repeated:

1. First, deduplicate the array, and then determine whether the array elements are repeated by judging the array length.

/** 
 * 判断数组内有无重复元素 
 * @param args 
 * @return true 有重复 | false 无重复 
 */  
public static boolean hasRepeat(Object[] args){  
    Set<Object> tempSet = new HashSet<Object>();  
    for (int i = 0; i < args.length; i++) {  
        tempSet.add(args[i]);  
    }  
    if(args.length == tempSet.size()){  
        return false;  
    }else{  
        return true;  
    }  
}

2. Compare the elements in the array for equality through double loops to determine whether the elements are repeated

1. Two for loops, determine whether they are equal in sequence, or call Arrays.sort() first, Then use Arrays.binarysearch() to compare

2, convert the array into a string separated by special characters, and then use \1 in the regular expression, which is the first matching result. This method Higher efficiency.

public void testMethod(){  
   int []b=new int[]{1,3,5,6,2,4,20,9};  
   boolean flag=true;  
   for(int i=0;i<b.length-1;i++){  
    for(int j=i+1;j<b.length;j++){ //注意FOR嵌套的用法  
     if(b[i]==b[j]){  
      flag=false;  
      //break;  
     }else{  
      flag=true;  
      //break;  
     }  
    }  
     
   }  
   if(flag){  
    System.out.println("不重复");  
   }else{  
    System.out.println("重复");  
   }  
}

For more java knowledge, please pay attention to java basic tutorial.

The above is the detailed content of Java determines whether array elements are repeated. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn