[英]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:我有一个存储 Team(运动队)类型对象的 List,我想显示所有相同类型球队的排名:
static List<Team> teams = new ArrayList<>();
Team class is generic, it accept parameter types of some clases like: Fotbal, Basketball, etc. Team class 是通用的,它接受一些类的参数类型,如:Fotbal、Basketball 等。
With the following method I wish to display the ranks of teams of one type, for ex.使用以下方法,我希望显示一种类型的团队的排名,例如。 to display all fotbal teams ranking:
显示所有 fotbal 球队排名:
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.在此 state 中,该方法返回所有团队,而与运动类型无关。
This is my Team class declaration:这是我的团队 class 声明:
public class Team<T extends Player > extends Championship implements Comparable<Team<T>>{
}
You could use the instanceof keyword like this:您可以像这样使用 instanceof 关键字:
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?但也许一个团队应该只是一个通用的 object 并带有一个存储其类型的
enum
字段? Then you could compare it with然后你可以将它与
if (team.getType() == BASEBALL)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.