Roman Racca
Roman Racca

Reputation: 37

How to initialize variables from list in Java?

Suppose that I have created a list of names, eg:

Martin 
Paul 
Diego 
Damian 
etc. 

And I need to initialize respectively, for example (psuedocode):

Martin int = 0; 

And you create them an Output same for all, which is (psuedocode):

System.out.println (Martin + "Martin foundn"; 

How to do this automatically?

Upvotes: 1

Views: 100

Answers (2)

davek
davek

Reputation: 22895

You could define them as an Enum with (hopefully immutable) behaviour:

enum Person {
    MARTIN {
        public String pName() {
            return "something here";
        }
        public int pNumber() {
            return 0;
        }
    },
    PAUL {
        public String pName() {
            return "something else";
        }
        public int pNumber() {
            return 1;
        }
    };

    public abstract String pName();
    public abstract int pNumber();
}

Upvotes: 1

Unihedron
Unihedron

Reputation: 11041

You're looking for a HashMap, which maps keys to their values.

HashMap<String, Integer> map = new HashMap<>();
map.put("Martin", 0);
// etc
System.out.println(map.get("Martin"));

You can see the official documentation for what you can do this with, but this is the class you will need specifically.

Upvotes: 3

Related Questions