Home > OS >  How to implement a for loop of objects in two arrayLists at once in Java?
How to implement a for loop of objects in two arrayLists at once in Java?

Time:12-30

New to programming, please forgive if this is stupid

I'm trying to loop through two arrayLists at once in Java. Below is my code and beneath that is the code I am trying to implement (if this is possible).

In a class "Tournament", it creates and stores Champion objects. I have two arrayLists: championList(this stores all hard coded champion objects into the game) and teamList(champion objects are added to a players team).

I want to check if the champion object in question (the parameter in the method) exists by looping through both arrayLists and returning a specified int if it doesn't.

Working code:

    public int retireChamp(String nme){
    for(Champion temp: championList)
    {
       if(temp.getName().equals(nme)) 
       do something etc...
    }

Code I want to implement if possible

    public int retireChamp(nme){
    for(Champion temp: championList && teamList)
    {
       do something...
    }

CodePudding user response:

If I understand correctly, your lists do not always seem to contain the same elements, and if they do, not necessarily in the same order. What you actually want to do is not iterate over the two lists at the same time but check if there is an element in both lists that has the same attribute as the passed parameter. You can do this one after the other:

public int retireChamp(nme){

    boolean inChampList = false;
    boolean inTeamList  = false;

    for(Champion temp: championList) {
       if(temp.getName().equals(nme)){
          inChampList = true;
          break;
       }
    }

    for(Champion temp: teamList) {
       if(temp.getName().equals(nme)){
          inTeamList = true;
          break;
       }
    }

    if(inChampList && inTeamList) {
       //your logic here - nme is in both lists
    } else if (inChampList ^ inTeamList) {
       //your logic here - nme is in one of the lists
    } else {
       //your logic here - nme is in none of the lists
    }
}
  • Related