0

I get "Exception in thread "main" java.lang.OutOfMemoryError: Java heap space" exception while adding values in arrayList. This is just a example

public class Test     {

    public static void main(String[] args)
    {
        Test t= new Test();
        ArrayList<ArrayList<String>> deleteError = new  ArrayList<ArrayList<String>>();
        for(TableItem item : items) // loop moves 800 times
        {
            for(String Element_ID : checkelementID) // another loop which check element ids which moves for 800 again
            {
                t.deleteErrorInArrayList("1", "GEN_err", "11", deleteError);
                t.deleteErrorInArrayList("1", "Greater_than", "11", deleteError);

                t.deleteErrorInArrayList("1", "GEN_err", "16", deleteError);
                t.deleteErrorInArrayList("1", "Greater_than", "16", deleteError);
            }
        }


    }
    public void deleteErrorInArrayList(String rowID,String message,String column,ArrayList<ArrayList<String>> mainlist)
    {
        ArrayList<String> list = new ArrayList<String>();
        list.add(rowID);
        list.add(message);
        list.add(column);
        mainlist.add(list);
        list = null;
    }
}

Please help me. How to optimize above code so i can reduce time and remove exception.

JavaHopper
  • 5,567
  • 1
  • 19
  • 27
  • Possible duplicate of [java.lang.OutOfMemoryError: Java heap space](http://stackoverflow.com/questions/1596009/java-lang-outofmemoryerror-java-heap-space) – Ravindra babu Aug 08 '16 at 17:26

1 Answers1

0

Given that all elements of the inner lists have the same structure (three strings), you could do better by storing an array (String[]) instead of an ArrayList.

Further: you are wasting space by storing strings, when you (apparently) only need some codes. I'd try replaceing GEN_err and Greater_than by some integer encoding, and store arrays of three integers (or shorts, or bytes) instead and you should use less memory.

leonbloy
  • 73,180
  • 20
  • 142
  • 190
  • 1
    But i haven't pre-defined size for String[]. Data might be increased or decreased. – Rahul Prajapati Aug 08 '16 at 05:13
  • Well, it's hard for us to give tips for optimizing some code if you don't give us the specs (only code). – leonbloy Aug 08 '16 at 13:01
  • I think I have given entire main class just to understand the scenario. Let me know if anything else you required. – Rahul Prajapati Aug 08 '16 at 13:52
  • I have already given two suggestions, they depend on whether you can 1) replace strings by integer codes, and 2) assume all sublists have sizes 3 - your code does not (cannot) make that clear, you must state that. – leonbloy Aug 08 '16 at 13:59