Search code examples
javasortingdynamic-arrays

class that simulates bi-dimensional table in JAVA


public class table 
{
private int raw=0;
private int column=0;
private List<ArrayList<Integer>> TABLE ;
private static int COUNT_ELEMENTS_IN_RAW=0;
private static int COUNT_ELEMENTS_TOTAL=0;
private List<Integer> singleRaw ;
public table()
{
    TABLE = new ArrayList<ArrayList<Integer>>();
    singleRaw = new ArrayList<Integer>();
}
public void addELEMENT(Integer value)
{   
    if(!TABLE.equals(null))
    {

        singleRaw.addAll(TABLE.get(raw));
        singleRaw.add(value);
        COUNT_ELEMENTS_IN_RAW++;
        if(COUNT_ELEMENTS_IN_RAW%14==0)
        {
            raw++;
            COUNT_ELEMENTS_IN_RAW=0;
            COUNT_ELEMENTS_TOTAL++;
        }
    }
}
}

here i´m trying to simulate 2-dimensional table(xy),function addELEMENT performs insertion into the "table". anybody can explain me why gives me that error ?

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at pt.iul.poo.games.table.addELEMENT(table.java:27)

Solution

  • Your problem is in this line:

    singleRaw.addAll(TABLE.get(raw));
                     ^^^^^^
    

    The Exception you're getting is very informative:

    Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    

    It's telling you that the List is of size 0, and you're trying to TABLE.get(raw)); where raw is 0, but if TABLE is of size 0, you can't get the element at 0. You do have an List but it's empty, you didn't insert anything to it.

    You should also change if(!TABLE.equals(null)) to if(TABLE != null), because if TABLE is null, this will throw a NPE since it'll be evaluated to !null.equals(null)

    Also, try to follow Java Naming Conventions and change TABLE to table and your class to Table.