我尝试编写方法,给出第一个重复出现的char但是当字符串没有任何时我得到这个错误:
java.lang.ArrayIndexOutOfBoundsException: 3
码:
static char firstReccuring(char str[]){
HashSet<Character> map = new HashSet<>();
for(int i=0; i<=str.length; i++ ) {
char ch = str[i];
if(map.contains(ch)) {
return ch;
}else {
map.add(ch);
}
}
return '0';
}
public static void main(String[] args) {
String str = "abc";
char[] arr = str.toCharArray();
System.out.println(firstReccuring(arr));
}
把i<=str.length
变成i<str.length
你的String只有三个字符,这意味着数组中最大的索引是2
for(int i=0; i<=str.length; i++ ) {`
删除等于因为如果字符串的长度为n,则最大可访问索引为n-1