Nathalie
Nathalie

Reputation: 113

Why does my array contain the same elements?

Java beginner here. I'm trying to add Result objects from an ArrayList to an Array (to be sorted later). I know ArrayLists probably would work better but I'm required to use at least one array in this assignment.

In my code, I have made a copy of an array that is an instance of the class Event and I'm trying to iterate through it and add the best results from different Participant objects. When I run this, merely the best result of the most recently added Participant gets added to the array (same object in all indexes). How do I add the result from all of the objects in the list?

public void createBestResultArray(Event e) {        
    resultArray = Arrays.copyOf(resultArray,e.getParticipantAmount());

    for(Participant p1 : participantsInEvent){
          for (int i = 0; i < resultArray.length ; i++){
             resultArray[i] = p1.getBestResult(e);
          } 
    }
    System.out.print(Arrays.toString(resultArray));
}

Upvotes: 1

Views: 112

Answers (1)

Chetan Kinger
Chetan Kinger

Reputation: 15212

You need to change your for-loop. Assuming that participantsInEvent is a List, change your loop as follows :

for(int i=0;i<participantsInEvent.size();i++) {
    resultArray[i] = participantsInEvent.get(i).getBestResult(e) ;
}

The first for-loop in your question takes a participant from participantsInEvent. The second for loop then copies that participants best result to all index positions in the resultArray. This process is repeated for each participant. You are naturally left with the resultArray containing the best result for the last participant that was present in the participantsInEvent collection.

Upvotes: 2

Related Questions