简体   繁体   中英

Java: How do I return only objects of one parameter type from a List that contains more parameter types?

I have this List that stores objects of type Team (sport teams) and I want to display the ranking of all teams of the same type:

static List<Team> teams = new ArrayList<>();

Team class is generic, it accept parameter types of some clases like: Fotbal, Basketball, etc.

With the following method I wish to display the ranks of teams of one type, for ex. to display all fotbal teams ranking:

static  void classament() {
        Collections.sort(Championship.teams);
        for (Team i : teams) {
            System.out.println(i);
        }
     }

In this state the method return all teams irrespective of the type of sport.

This is my Team class declaration:

public class Team<T extends Player  > extends Championship implements Comparable<Team<T>>{

}

You could use the instanceof keyword like this:

if (team instanceof BasketballTeam) {
    System.out.println(team);
}

and this would work. But maybe a team should just be a generic object with an enum field storing its type? Then you could compare it with

if (team.getType() == BASEBALL)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM