Skip to content
Advertisement

LinkedList: java.lang.OutOfMemoryError: Java heap space

I’m trying to make a graph implementation for an assignment, which has Graph(GraphImp) objects and Node(NodeImp) objects.

Node objects contain a reference to their Graph, x & y co-ordinates and a name.

The Graph object contains a linked list of its Nodes.

The problem occurs when I try to add a Node into the middle of the List of Nodes (Appending to the end works fine). The program runs out of heap space. I’m not sure why this is occurring though, since the complexity of inserting to a LinkedList should be O(1), and Java (I believe) uses pointers, rather that the objects themselves. I’ve also tried an arraylist

Making the heap larger is not an option in this instance, and (as far as I understand) should not be the source of the problem.

Thanks in advance.

Here is the error:

JavaScript

Here is the Code:

JavaScript

Advertisement

Answer

The problem is that you are not exiting your loop after inserting the new node in the middle of the list. Your code will try to insert the same node an infinite number of times, hence the OOM.

Try this:

JavaScript

As an aside, your insertion is pretty inefficient. Since you know the list is already sorted you could use a binary search to find the insertion point rather than an O(n) scan of the list. Your current implementation is O(n^2) to insert n items, but it could be O(n log n).

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement