如何避免从arraylist

时间:2015-09-30 13:50:56

标签: java arraylist

我正在尝试做一个arraylist的子字符串,但是当列表为空时我得到索引超出绑定的异常 这是我的代码

if(interviewTimingToFrom1.size()>0) {
    for (int i = 0; i < interviewTimingToFrom1.size(); i++) {       
        String str = interviewTimingToFrom1.get(i).substring(0, 
                                interviewTimingToFrom1.get(i).length() - 3);
        subInterviewTiming1.add(str);
    }
}

if (interviewTimingToFrom2.size()>0) {
    for (int i = 0; i < interviewTimingToFrom2.size(); i++) {
        String str = interviewTimingToFrom2.get(i).substring(0,
                               interviewTimingToFrom2.get(i).length() - 3);
        subInterviewTiming2.add(str);
    }
}       

interviewTimingToFrom2interviewTimingToFrom1为空时,我的索引超出界限如何解决此问题

1 个答案:

答案 0 :(得分:2)

试试这个,这可以帮助您避免异常。

String str = interviewTimingToFrom2.get(i).substring(0, interviewTimingToFrom2.get(i).length() > 3 ? interviewTimingToFrom2.get(i).length() - 3 : interviewTimingToFrom2.get(i).length());