Re: Newbie Question: Creating a dynamic object...
Taria wrote:
generate new node name
NodeInfo (newNodeName here) = new NodeInfo();
<data manipulation after this>
Janusch wrote:
use ArrayList, code for Java 1.4:
Java 1.4 is old. Use Java 6.
There are lots of ways to do what Taria asked. [Array]List was not the most
obvious to me. More obvious were Map and simply creating what you need when
you need it.
Map:
Map <String, Node<Foo>> nodes = new HashMap <String, Node<Foo>> ();
....
Node<Foo> node = nodes.get( name );
if ( node == null )
{
node = new Node<Foo>( new Foo(name) );
nodes.put( name, node );
}
....
Simply creating:
while ( hasMoreToDo() )
{
String name = getName();
Foo foo = new Foo( name );
Node<Foo> node = new Node<Foo> (foo);
doSomething( node );
}
The only real difference between the two is that the Node reference is kept
around in the Map alternative, by dint of being in the Map.
The problem with the List approach is that it requires that you know the index
of the Node, where you asked to find it via the name.
Note that a Map can be indexed by any object type, not just String. You could
key it by Foo, for example, if Foo were a custom object stored in a Node.
Map <Foo, Node<Foo> > nodes = new HashMap <Foo, Node<Foo> > ();
...
Foo foo = getAFoo();
Node<Foo> node = nodes.get( foo );
etc.
<http://java.sun.com/javase/6/docs/api/java/util/Map.html>
--
Lew