Index out of Bounds issue in Java

So I have this code for an assignment in university, it's giving me an index out of bounds for some reason I don't know, the purpose of this method is to invert routeLocation (which is an ArrayList) and then takes the inverted ArrayList & adds it to the String fullRoute with a comma between every element in the ArrayList.

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) {
    int w = temp.size();
    while (i < w) {
        fullRoute = fullRoute + "," + temp.get(i);
    return fullRoute;


int x = this.getRouteLocations().size();

should be

int x = this.getRouteLocations().size()-1;

And you also need to change while (x > 0) { to while (x >= 0) {.

Currently in your first iteration you're trying to access the elements at the index equals to the size of the list. Since it's 0 base indexed, they goes from 0 to size - 1.

I.e for a list of two elements let's say myList = List(5,15) (so the size of the list is 2) you have:

index value
0       5
1      15

In your first iteration you're doing myList.get(x); which is equivalent to myList.get(2); as you initialized x with the size of your list.

Also note that you don't need to create a temporary list. A simple loop that going through the end to the front of the original list would suffice, so something like this:

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

Need Your Help

Constraints with Label on Image View

ios user-interface debugging swift2 constraints

In my app I have a Image for my background with labels on top of it that are not moving correctly on the iPhone 6 Plus. I am having trouble with the constraints to make the labels move correctly wi...

present live data in JTextArea using Swing

java swing jtextarea event-dispatching

Don't know if it's stupid or reasonable question.