This week's book giveaway is in the Java in General forum.
We're giving away four copies of Think Java: How to Think Like a Computer Scientist and have Allen B. Downey & Chris Mayfield on-line!
See this thread for details.
Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Implementing N-Ary tree data structure in Java

 
Srinivas Redd
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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

<movie>
<name>Titanic</name>
<language>english</language>
</movie>

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,
Srinivas.
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could use a java.util.LinkedList or java.util.ArrayList instead of an array.
 
Campbell Ritchie
Sheriff
Posts: 48910
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Pie
Posts: 20526
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic