Java: Add elements to arraylist with FOR loop where element name has increasing number

后端 未结 8 712
故里飘歌
故里飘歌 2020-12-19 08:26

I have an arraylist where I want to add elements via a for loop.

Answer answer1;
Answer answer2;
Answer answer3;

ArrayList answers = new Array         


        
相关标签:
8条回答
  • 2020-12-19 08:32

    why you need a for-loop for this? the solution is very obvious:

    answers.add(answer1);
    answers.add(answer2);
    answers.add(answer3);
    

    that's it. no for-loop needed.

    0 讨论(0)
  • 2020-12-19 08:32

    Put the answers into an array and iterate over it:

    List<Answer> answers = new ArrayList<Answer>(3);
    
    for (Answer answer : new Answer[] {answer1, answer2, answer3}) {
        list.add(answer);
    }
    

    EDIT

    See João's answer for a much better solution. I'm still leaving my answer here as another option.

    0 讨论(0)
  • 2020-12-19 08:36

    That can't be done with a for-loop, unless you use the Reflection API. However, you can use Arrays.asList instead to accomplish the same:

    List<Answer> answers = Arrays.asList(answer1, answer2, answer3);
    
    0 讨论(0)
  • 2020-12-19 08:40

    There's always some reflection hacks that you can adapt. Here is some example, but using a collection would be the solution to your problem (the integers you stick on your variables name is a good hint telling us you should use a collection!).

    public class TheClass {
    
        private int theField= 42;
    
        public static void main(String[] args) throws Exception {
    
            TheClass c= new TheClass();
    
            System.out.println(c.getClass().getDeclaredField("theField").get(c));
        }
    }
    
    0 讨论(0)
  • 2020-12-19 08:47

    Thomas's solution is good enough for this matter.

    If you want to use loop to access these three Answers, you first need to put there three into an array-like data structure ---- kind of like a principle. So loop is used for operating on an array-like data structure, not just simply to simplify typing task. And you cannot use FOR loop by simply just giving increasing-number-names to the elements.

    0 讨论(0)
  • 2020-12-19 08:47

    Using Random function to generate number and iterating them on al using for loop

    ArrayList<Integer> al=new ArrayList<Integer>(5);
        for (int i=0;i<=4;i++){
    
           Random rand=new Random();
            al.add(i,rand.nextInt(100));
            System.out.println(al);
        }
    System.out.println(al.size());
    
    0 讨论(0)
提交回复
热议问题