0

Suppose I take an integer user input - 17. Now I want to create 17 "Node" class objects. And they'll be named like node1, node2, ..., node17.

How to achieve that?

Buggy Coder
  • 383
  • 5
  • 17
  • Why you want to do this? – kaetzacoatl Jun 22 '14 at 14:01
  • 3
    Objects don't have names, unless they have a name attribute. Use a loop, create 17 Node instances, each with the desired name, and store them in a List or a Node[] array. – JB Nizet Jun 22 '14 at 14:02
  • 1
    @JBNizet looks like he wants to create objects with reference names as node1, node2,... – Nullpointer Jun 22 '14 at 14:03
  • 1
    What do you mean with _17 "Node" class objects_? 17 objects of class Node or 17 classes inheriting from Node? – blafasel Jun 22 '14 at 14:04
  • If you really need to materialize the code for individual node variables consider [writing a code generator](http://pragmatictips.com/29) or use a [templating engine(like velocity)](http://www.onjava.com/pub/a/onjava/2004/05/05/cg-vel1.html) to do that more conveniently. But try to stick on the "conventional" methods like arrays or lists in this case. – isaias-b Jun 22 '14 at 14:06
  • @JBNizet I meant reference names. – Buggy Coder Jun 22 '14 at 14:08
  • 1
    Use an array or a List. That's exactly what they're for: storing 0 to N references. – JB Nizet Jun 22 '14 at 14:09

1 Answers1

3

Don't. What you are asking is a bad idea.

What you can do is add multiple new objects to an Array or Collection.
If you don't care about names an ArrayList<Node> will do the job.
If you do need names then make them keys in a HashMap<String, Node> or similar.

public List<Node> makeThisManyNodes(int count) {
    List<Node> nodes = new ArrayList<Node>();
    for (int i=0; i<count; i++) {
        nodes.add(new Node());
    }
    return nodes;
}

static final String NODE_BASE_NAME = "node_%d";

public Map<String, Node> makeThisManyNodes(int count) {
    Map<String, Node> nodes = new HashMap<String, Node>();
    String key;
    for (int i=0; i<count; i++) {
        key = String.format(NODE_BASE_NAME, i);
        nodes.put(key, new Node());
    }
    return nodes;
}
indivisible
  • 4,892
  • 4
  • 31
  • 50