jQuery in Action, 3rd edition
The moose likes Java in General and the fly likes Implementing N-Ary tree data structure in Java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Implementing N-Ary tree data structure in Java" Watch "Implementing N-Ary tree data structure in Java" New topic

Implementing N-Ary tree data structure in Java

Srinivas Redd

Joined: Mar 23, 2006
Posts: 17

I am writing a program to convert the SOAP message to a tree structure. The tree that I am going to create should be a N-Ary tree. I have created a class like the below one which is a data structure that acts as a node.Each element in the SOAP message is taken as an object.Complex elements( one object ) will maintain link to simple elements (objects)

Class nAryTree
String name;
String type;
String value;
nAryTree nodes[] = new nAryTree[100];

**** some functions goes on here ***

I have taken an array to point to simple elements in an array which is set at a size of 100. Assume a complex element movie which has name,language as the only two elements


I am wasting lot of memory here as I created 100 objects in a class but has only two nodes.

Can somebody suggest me how can I better implement this without declaring arrays? I am interested to create my own data structure not any collections.So please suggest me how can I modify above class to manage the memory in an efficient way.

Thanks in advance,

Srinvasa Reddy Thamma,<br />Chennai,India.
Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
You could use a java.util.LinkedList or java.util.ArrayList instead of an array.

Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 43995
Do you really need a tree at all? The structure of XML nests attributes inside other attributes, but that may match an object structure better.Is there any way you can get the XML into objects like that? Then a List<Movie> implementation can make its use easy.
Rob Spoor

Joined: Oct 27, 2005
Posts: 20079

Originally posted by Srinivas Redd:
I am wasting lot of memory here as I created 100 objects in a class but has only two nodes.

Actually you have only created an array that can store 100 objects. Each element of that array is still null.

But I agree with Garrett - a List would be much better:

I also agree with Campbell. If the structure is fixed and limited, you can map the XML tree onto objects and only store those in a List.

How To Ask Questions How To Answer Questions
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
subject: Implementing N-Ary tree data structure in Java
It's not a secret anymore!