Java中的索引越界问题

Java中的索引越界问题,java,indexing,indexoutofboundsexception,bounds,out,Java,Indexing,Indexoutofboundsexception,Bounds,Out,我有一个大学作业的代码,它给了我一个超出范围的索引,原因我不知道,这个方法的目的是反转routeLocation(一个ArrayList),然后取反转的ArrayList&在ArrayList中的每个元素之间用逗号将它添加到字符串fullRoute中 public String getFullRoute() { int x = this.getRouteLocations().size(); int i = 0; fullRoute = this.getRouteLoca

我有一个大学作业的代码,它给了我一个超出范围的索引,原因我不知道,这个方法的目的是反转routeLocation(一个ArrayList),然后取反转的ArrayList&在ArrayList中的每个元素之间用逗号将它添加到字符串fullRoute中

public String getFullRoute() {
    int x = this.getRouteLocations().size();
    int i = 0;
    fullRoute = this.getRouteLocations().get(0) + ",";
    ArrayList<FunRide> temp = new ArrayList<FunRide>();
    while (x > 0) {
        temp.add(this.getRouteLocations().get(x));
        x--;
    }
    int w = temp.size();
    while (i < w) {
        fullRoute = fullRoute + "," + temp.get(i);
        i++;
    }
    return fullRoute;
}
公共字符串getFullRoute(){
int x=this.getRouteLocations().size();
int i=0;
fullRoute=this.getRouteLocations().get(0)+“,”;
ArrayList temp=新的ArrayList();
而(x>0){
temp.add(this.getRouteLocations().get(x));
x--;
}
int w=温度大小();
而(i
应该是

int x = this.getRouteLocations().size()-1;
您还需要将
while(x>0){
更改为
while(x>=0){

当前,在第一次迭代中,您试图访问索引等于列表大小的元素。因为它是0基索引,所以它们从0变为大小-1

例如,对于两个元素的列表,假设
myList=list(5,15)
(因此列表的大小为2),您有:

index value
0       5
1      15
在第一次迭代中,您使用列表的大小初始化
x
,这相当于
myList.get(2);

还要注意的是,您不需要创建临时列表。一个简单的循环,从原始列表的末尾到前面就足够了,因此如下所示:

public static String getFullRoute() {
    int x = routeLocation.size()-1;
    StringBuilder sb = new StringBuilder(routeLocation.get(0)).append(',');
    while (x >= 0) {
        sb.append(',').append(routeLocation.get(x));
        x--;
    }
    return sb.toString();
}

谢谢你解决了这个问题,但是你能告诉我为什么会发生这个错误吗?:)@user3442961你在我的解释中不明白什么?由于某些原因,我的浏览器没有显示完全回复,非常感谢
public static String getFullRoute() {
    int x = routeLocation.size()-1;
    StringBuilder sb = new StringBuilder(routeLocation.get(0)).append(',');
    while (x >= 0) {
        sb.append(',').append(routeLocation.get(x));
        x--;
    }
    return sb.toString();
}