我正在尝试做一个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);
}
}
当interviewTimingToFrom2
和interviewTimingToFrom1
为空时,我的索引超出界限如何解决此问题
答案 0 :(得分:2)
试试这个,这可以帮助您避免异常。
String str = interviewTimingToFrom2.get(i).substring(0, interviewTimingToFrom2.get(i).length() > 3 ? interviewTimingToFrom2.get(i).length() - 3 : interviewTimingToFrom2.get(i).length());