-3

I have a question about param, what param to present the class, such as if I findBuildingsType( buildingEntities, Village) it will return all village building as a result

enter image description here

geocodezip
  • 158,664
  • 13
  • 220
  • 245
  • 3
    Hello, Zhenwei, welcome to the site. It's not clear what you are asking. Please include the code as text and not as an image. Check [ask] – RubioRic Jul 15 '21 at 06:08
  • don't look for instanceof, use currBuildings.getClass().getName() or similar, or pass [Type].class instead of the name of the class and compare classes – Stultuske Jul 15 '21 at 06:09
  • @RubioRic it's quite clear what is going wrong: if ( myInteger instanceof "Integer") is not the same as if ( myInteger instanceof Integer ) – Stultuske Jul 15 '21 at 06:10
  • @Stultuske Ah, I didn't see that type was an argument of the method and a String. – RubioRic Jul 15 '21 at 06:12
  • Does this answer your question? [Test if object is instanceof a parameter type](https://stackoverflow.com/questions/5734720/test-if-object-is-instanceof-a-parameter-type) – Izruo Jul 15 '21 at 06:30

1 Answers1

1

Welcome.

You can deliver a Class via arguments like this:

private List<Building> findBuildingsType(List<Building> buildings, Class<? extends Building> typ) {
    List<Building> re = new ArrayList<>();
    
    for (Building building : buildings) {
        if (typ.isInstance(building)) {
            re.add(building);
        }
    }
    
    return re;
}

Especially for your problem consider using streams:

List<Building> buildingsOfTypeMansion = buildings.stream().filter(building -> building instanceof Mansion).collect(Collectors.toList());
Leo
  • 36
  • 2