0

Although I know usage of Java Vectors is discouraged as its deprecated, I am stuck with a legacy code where in I don't have the luxury to modify it.

I am getting an OutOfMemoryError while trying to addElement to the Vector. Following below is my code snippet. Please let me know if I can improve the below code.

 /*objOut is the Vector Object.
     idx is incoming integer argument. 
     Val is some Object
   */
    int sz = objOut.size();
                    if (idx == sz) {
                        objOut.addElement(val);
                    } else if (idx > sz) {
                        for (int i = (idx-sz); i>0; i--) {
                            objOut.addElement(null); // Code through OutOfMemory in this line
                        }
                        objOut.addElement(val);
                    } else {
                        objOut.setElementAt(val, idx);
                    }
Vinod Jayachandran
  • 3,726
  • 8
  • 51
  • 88
  • 2
    that is hardly enough context, you dont get outofmemory from one addElement call. Give us more context or knowledge. Is it performed in a loop? If yes, when does the loop abort? etc... – user2504380 Oct 09 '14 at 09:56
  • Increase JVM heap space with -Xmx, see http://stackoverflow.com/q/37335/1140748 – alain.janinm Oct 09 '14 at 09:58
  • You are trying to add a lot of items. When the OutOfMemoryError occured means it need more heap memory, increase the heap space it may resolved. – newuser Oct 09 '14 at 09:59

1 Answers1

1

In your program, you are trying to allocate n number of objects.
Your OS allocates some space to your JVM to work with and that space is called heap space. You get OutOfMemoryError when all of your heap space is filled and no more space is left to allocate for new objects.

So what you should do is increase your heap space with -Xmx like this:

java -Xmx 1024m YourClassName  

This will allocate a heap space of 1024 MB's (1 GB) for your program. You may request for heap space as per your requirement.

Aditya Singh
  • 2,343
  • 1
  • 23
  • 42