小编cod*_*nja的帖子

toCharArray,Index out of bounds

有人可以告诉我为什么.toCharArray()行给出了一个Index Out of Bounds异常吗?为什么它甚至为String提供索引0大小为0的异常?我还没有定义一个字符串数组?!

此外,此代码应该在O(n)时间运行吗?

import java.util.ArrayList;
import java.util.List;


public class FirstNonRepeating {


public static List<Character> list = new ArrayList<Character>();
public static List<Character> list2 = new ArrayList<Character>();

public static String res(String x) {
    char[] y = x.toCharArray();

    for(char c:y){
        list2.add(c);
        if(list.contains(c)){
            list2.remove(c);
        }
        else{
            list2.add(c);
        }
    }

    if(list2.isEmpty()){
    return "NONE";
    }

    else return (""+list.get(0));

    }

public static void main(String[] args) {

    String a="Google";
    String z=res(a);
    System.out.println(z);
}

}
Run Code Online (Sandbox Code Playgroud)

java indexoutofboundsexception

0
推荐指数
1
解决办法
498
查看次数

标签 统计

indexoutofboundsexception ×1

java ×1