Search code examples
javasortingarraylistindexoutofboundsexceptionbubble-sort

Experiencing out of bounds exception error with array list in Java


I'm trying to create a bubble swap method for arraylists in Java, but I've run into an error. Here's my code:

public static void BubbleSort()
{
    list.remove("");
    for (int i = list.size(); i > 0; i--)
    {
        for (int j=0; j < i; j++)
        {
            if(Integer.valueOf((String) list.get(j)) < Integer.valueOf((String) list.get(j + 1)))
                Swap(list.get(j), list.get(j + 1));
        }
    }
    System.out.println(list);
}

And here's the Swap method it calls:

public static void Swap(Object object, Object object2)
{
    Object spotC = object; 
    list.set(list.indexOf(object), object2); 
    list.set(list.indexOf(object2), spotC);
}

Solution

  • Try this

    public static void BubbleSort()
    {
        for (int i = 0; i < list.size(); i++)
        {
            for (int j=i+1; j < list.size(); j++)
            {
                if(Integer.valueOf(list.get(i).toString()) > Integer.valueOf(list.get(j).toString()))
                    Swap(list.get(j), list.get(i));
            }
        }
        System.out.println(list);
    }
    
    
    public static void Swap(Object object, Object object2)
    {
        Object spotC = object; 
        list.set(list.indexOf(object), object2); 
        list.set(list.indexOf(object2), spotC);
    }