AterCZ
AterCZ

Reputation: 17

Comparing element values in an ArrayList

I'm trying to find an element in the ArrayList "minions" with the highest "evilLevel" (that's defined in another class).

public Minion(String name, int evilLevel, boolean onMission) - from class Minion


    private Set<Minion> minions;
    int maxEvilLevel = 0;
    Minion theMostEvilMinion;  

     public MinionRegister(){


        minions = new HashSet<Minion>();
      }

     public Minion getMostEvilMinion(){
        if(minions.isEmpty()){
            return null;
        }


        for(Minion m : minions){
            if(m.getEvilLevel() > maxEvilLevel) {
                maxEvilLevel = m.getEvilLevel();
                Minion theMostEvilMinion = m;
            }
        }
        return theMostEvilMinion;
    }

Unfortunately the method returns "null"

Upvotes: 0

Views: 46

Answers (1)

khelwood
khelwood

Reputation: 59210

Here:

for(Minion m : minions){
    if(m.getEvilLevel() > maxEvilLevel) {
        maxEvilLevel = m.getEvilLevel();
        Minion theMostEvilMinion = m;
    }
}
return theMostEvilMinion;

Inside the for loop, you declaring and setting a local variable theMostEvilMinion, which is then forgotten, because it is declared inside that block.

Then after the loop, you return the instance variable theMostEvilMinion, a different variable which is declared at the top of your class.

You need to declare and set one local theMostEvilMinion variable and then return it.

Minion theMostEvilMinion = null;
int maxEvilLevel = 0;
for (Minion m : minions) {
    if (m.getEvilLevel() > maxEvilLevel) {
        maxEvilLevel = m.getEvilLevel();
        theMostEvilMinion = m;
    }
}
return theMostEvilMinion;

Then you can also delete the theMostEvilMinion and maxEvilLevel instance variables.

Upvotes: 2

Related Questions