Search code examples
javaobjectdynamicobject

How to dynamically create class objects with serial naming?


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?


Solution

  • 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;
    }