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?

7
  • Why you want to do this? Commented Jun 22, 2014 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<Node> or a Node[] array. Commented Jun 22, 2014 at 14:02
  • 1
    @JBNizet looks like he wants to create objects with reference names as node1, node2,... Commented Jun 22, 2014 at 14:03
  • 1
    What do you mean with 17 "Node" class objects? 17 objects of class Node or 17 classes inheriting from Node? Commented Jun 22, 2014 at 14:04
  • 1
    Use an array or a List. That's exactly what they're for: storing 0 to N references. Commented Jun 22, 2014 at 14:09

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.