Taylor Liss
Taylor Liss

Reputation: 593

How to check if an ArrayList contains an object from another class

I have two classes, a Fighter class and a Player class. The Player class contains an ArrayList called fleet that is populated with a player's ships.

I can add ships to the player's fleet without issue, but when I try check to see if a fighter is present in the player's fleet, it gives me an error saying Fighter cannot be resolved to a variable.

I'm confused as to why I can add a Fighter to fleet, but can't check to see if a Fighter is present in fleet.

Fighter.java

public class Fighter extends Ship {
    public Fighter(){
        super(9,1,1); //Sets attack and defense values
    }
}

Player.java

import java.util.ArrayList;
import java.util.Scanner;

public class Player {

    ArrayList<Ship> fleet = new ArrayList<Ship>();

    public void takeAHit(){
        if (fleet.contains(Fighter)){                  //Error happens here
            System.out.println("Fighter found");
        }
    }

    public void buildFleet(){

        Scanner userInput = new Scanner(System.in);

        System.out.println("How many fighters?");

        int fighters = Integer.parseInt(userInput.next());

        while (fighters > 0){
            fleet.add(new Fighter());
            fighters--;
        }

        userInput.close();

    }
}

Core.java

public class Core {

    public static void main(String[] args) {

        Player p1 = new Player();
        p1.buildFleet();
        p1.takeAHit();

    }
}

Upvotes: 1

Views: 5982

Answers (2)

mid
mid

Reputation: 433

Unfortunately, the contains method needs an instance of the class and not the class itself.
And to reference a class, you need to append .class to the name.

The best solution I can think of is to create a method that uses the instanceof keyword similar to:

public boolean isFighterInFleet() {
    for(Ship ship : this.fleet)
        if(ship instanceof Fighter)
            return true;
    return false;
}

Then use:

if (isFighterInFleet()){

instead of

if (fleet.contains(Fighter)){

Upvotes: 7

Deepak Singhal
Deepak Singhal

Reputation: 10864

In Java 8:

this.fleet.stream().filter(ship -> ship instanceof fighter).findFirst().isPresent() ;

Upvotes: 1

Related Questions