下面的例子用的是char数组,可以换成其他类型数组,就是要同时更换if 判断句里不同类型数组默认空值,比如int 默认是0 之类。
/**check whether the input array has duplicated elements
* @param input
* @return
*/
public boolean evaluateInput(char[] input) {
Set<Character> temp = new HashSet<Character>();
int inLength=0;
for (char n : input) {
if (n!='/u0000'){ // or: if(n!=0)
inLength = inLength+1;
temp.add(n);
}
}
System.out.println(input);
System.out.println(temp);
System.out.println("input length =" + inLength);
System.out.println("set length =" + temp.size());
return inLength == temp.size();
}
------------below is a more efficient code (might return before go through whole string)--------------
/** check whether the input string has duplicated char (the input string has empty values)
* @param str
* @return
*/
public boolean isUnique (String str){
Set<Character> temp = new HashSet<Character>();
for(char c : str.toCharArray()){
if (c != 0){ //white space does not count
if (temp.contains (c)) return false;
else temp.add(c);
}
}
return true;
}