-1

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

roeygol
  • 4,908
  • 9
  • 51
  • 88
Ayoub
  • 1,417
  • 14
  • 24
  • FWIW, what you want is called reflection (see this [question](http://stackoverflow.com/questions/37628/what-is-reflection-and-why-is-it-usef) ) – merours Jan 17 '15 at 11:55

3 Answers3

2

Add them to a List or array YourClass[] and iterate through them like this:

List<Cat> catsList = new ArrayList<>();
Cat[] catsArray = new Cat[3]; //alternatively
public CatHouse(){
    Cat bob = new Cat();
    Cat fluffy = new Cat();
    Cat tom = new Cat();
    catsList.add(bob);
    catsList.add(fluffy);
    catsList.add(tom);
    //alternatively
    catsArray[0] = bob;
    catsArray[1] = fluffy;
    catsArray[2] = tom;
}

then iterate through the list\array to do something:

public void groomAll(){
    for (Cat cat : catList){
       cat.groom();
    }
    //alternatively
    for (Cat cat : catArray){
       cat.groom();
    }
}
Angelo Alvisi
  • 480
  • 1
  • 4
  • 15
1

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));
}
Gent Ahmeti
  • 1,559
  • 13
  • 17
0

If vari is a local variable, it is not possible. If vari are all members of the class, then you can do it by using the Reflection API (see the methods Class.getField() and Class.getDeclaredField()), but it will be very inefficient. Much better to use collections, and find alternative options.

cris23
  • 94
  • 5