Search code examples
javapolymorphismjava-collections-api

How to make the name of a variable in java variable itself


for exemple if I have a lot of variables var1,var2,var3,.... how can i manipulate them easily using an index i

for(int i=1,i<n;++i)
    System.out.print(vari);

I know that it's not correct but I wanna know if there is a possibility to manipulate variables in this manner


Solution

  • Is there a reason why you wouldn't use a collection? For example an array, list or even a map.

    My answer would be to use one of these constructs, otherwise I don't believe there is an easier way.

    The closest thing I could come up with is this:

    Map<String, Object> map = new HashMap<>();
    for(int i=1; i<map.size(); i++) {
        System.out.println(map.get("var"+i));
    }