0

let's say i have

 public static Set<Cat> createCats() {
    HashSet<Cat> result = new HashSet<Cat>();
     for (int i = 0; i < 4; i++) {
         Cat cat= new Cat();
          result.add(cat);
     }

and i want to add to this set cat0, cat1,cat2, cat3

 public static Set<Cat> createCats() {
    HashSet<Cat> result = new HashSet<Cat>();
     for (int i = 0; i < 4; i++) {
         Cat cat /* + i */ = new Cat();
          result.add(cat /* + i */);
     }
  • 1) Java doesn't have dynamic variable names. 2) variable names are a **lot** less important than you think that they are, and even if you *could* do what you want, the variable name would not exist outside of the loop, so it's meaningless. – Hovercraft Full Of Eels Dec 26 '17 at 22:33
  • 1
    Questions like this pop up literally every day. If, say, `Cat cat3` is local to the loop, why does it matter to have a different name in each iteration? Why do you need a name at all? I mean, `result.add(new Cat())` would work just fine, no? – Sergey Kalinichenko Dec 26 '17 at 22:35
  • You Can use à Map with the Integer for key – Greg Artisi Dec 26 '17 at 23:47
  • If you really want to save the number, you can create a Integer property at cat class like CatId and you can set it with the i – Fernando Ortu Dec 27 '17 at 01:45

0 Answers0