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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

Notepad++7.3.1
Easy-to-use and free code editor

Atom editor mac version download
The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.