How do I shuffle two arrays in same order in java

前端 未结 6 753
温柔的废话
温柔的废话 2021-01-12 01:40

I\'ve got two arrays of question and answers

String questions[] = {
\"Q1?\",
\"Q2?\",
\"Q3?\"};

String answers[] = {
    \"A1?\",
    \"A2?\",
    \"A3?\"}         


        
6条回答
  •  被撕碎了的回忆
    2021-01-12 02:03

    You can rather shuffle a new array which holds the indices. And then get the elements from both array from the first index.

    List indexArray = Arrays.asList(0, 1, 2);
    
    Collections.shuffle(indexArray);
    
    String question = questions[indexArray.get(0)];
    String answer = answers[indexArray.get(0)];
    

    Of course, creating a class containing questions and answers would be a more OO way, as other answers suggest. That way, you would have to maintain just one List or array, as compared to 3 arrays in the current approach.

提交回复
热议问题