0

I have the following classes in my java project Wheels, Engine, Brake which all implement CarPart

Objects created are stored in an ArrayList<CarPart> parts variable.

I want to check three things:

  1. Does my car have any Wheels?
  2. Does my car have any Engine?
  3. Does my car have any Brake?

I can write the hasWheels function, then write literally the same code again but replace Wheels with Engine, then with Brake. Its all duplicate code. Is there a way where I can pass a parameter to a function like doesArrayContain(parts, Wheels)?


public boolean hasWheels(ArrayList<CarPart> parts) { for (CarPart part : parts) { if (part instanceof Wheels) return false; } return true; } 

Something like this

public boolean doesArrayContain(ArrayList<CarPart> parts, Type type) { for (CarPart part : parts) { if (part instanceof type) return false; } return true; } 
2
  • 2
    Yes. Pass a Class object and use its isInstance method. Commented Nov 2, 2019 at 4:24
  • @KevinAnderson What is the Type? This? doesArrayContain(ArrayList<CarPart> parts, Class type) Commented Nov 2, 2019 at 4:25

1 Answer 1

2

You can use the instanceOf method which is apart of the class, 'Class'

Also your logic seems to be flawed, you're returning false for when the list does contain. (unless you named it wrong?) So I swapped the return statements.

public boolean doesArrayContain(ArrayList<CarPart> parts, Class<? extends CarPart> type) { for (CarPart part : parts) { if (type.isInstance(part.getClass())) return true; } return false; } 

use it like doesArrayContain(myList, Wheels.class)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.