![](/img/trans.png)
[英]How can I get a class to print out a string variable from an arraylist of objects located in another class?
[英]How can I print an arraylist that is in one class, by a grouping from another class?
我正在尝试基于另一类的参数之一来打印一类中的arraylist。 这可能吗?
import java.util.ArrayList;
public class TVShow {
private String title;
private String summary;
private String releaseDate;
private ArrayList<Episode> episodeList;
public TVShow(String title, String summary, String releaseDate) {
this.title = title;
this.summary = summary;
this.releaseDate = releaseDate;
this.episodeList = new ArrayList<>();
}
public void addEpisode(Episode episode) {
episodeList.add(episode);
}
public printEpisodesInSeason(int seasonNr) {
// How can I make this method access the other class and
// print the episodeList by season number?
for (Episode episode : episodeList) {
return System.out.println(episode.);
}
}
}
public class Episode {
private int episodeNr;
private int seasonNr;
private String eTitle;
private int runTime;
public Episode(int episodeNr, int seasonNr, String eTitle, int runTime) {
this.episodeNr = episodeNr;
this.seasonNr = seasonNr;
this.eTitle = eTitle;
this.runTime = runTime;
}
}
编辑:我想我误解了这个问题。 您只想打印特定季节的情节。 可以通过按以下步骤在episodeList
上应用过滤器功能来完成此操作:
for (Episode episode : episodeList.stream().filter(episode -> episode.getSeasonNr() == seasonNr).collect(Collectors.toList()))
{ ... }
当然,这是假设您在编辑答案之前应用如下所述的getter setter模式。
filter
函数采用匿名函数,并将其应用于集合的所有成员。 这样,仅返回具有用户提供的季节编号的情节。 然后,foreach循环遍历结果集合。
您可以通过定义以下内容来公开Episode的成员:
public class Episode {
public int episodeNr;
public int seasonNr;
public String eTitle;
public int runTime;
public Episode(int episodeNr, int seasonNr, String eTitle, int runTime) {
this.episodeNr = episodeNr;
this.seasonNr = seasonNr;
this.eTitle = eTitle;
this.runTime = runTime;
}
}
但这被视为不良做法。 更好的方法是通过在Episode类中定义方法以返回该类的字段的值,例如:
public class Episode {
public int episodeNr;
public int seasonNr;
public String eTitle;
public int runTime;
public Episode(int episodeNr, int seasonNr, String eTitle, int runTime) {
this.episodeNr = episodeNr;
this.seasonNr = seasonNr;
this.eTitle = eTitle;
this.runTime = runTime;
}
public String getTitle() {
return this.eTitle;
}
}
这种做法称为getter和setter,它对代码的封装产生积极影响。 然后,您可以通过调用例如episode.getTitle()
来获得Episode成员的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.