![](/img/trans.png)
[英]Java Reflection - Getting value of nested object, list and array within object
[英]Return a list within an array list object java
我正在尝试返回具有指定座位数的对象列表。 我的ArrayList
有所有的对象,我想在一个条件下返回所有的 object。 它适用于系统 output,但它不返回列表。 我想返回至少 329 个座位的不同 object。
List<Aircraft> aircraft = new ArrayList<>();
public List<Aircraft> findAircraftBySeats(int seats ) { // seats = 329
for(int i =0; i<aircraft.size(); i++) {
if (aircraft.get(i).getSeats() >= seats) {
String seatss = aircraft.get(i).getModel();
Aircraft a = new Aircraft();
a.setModel(seatss);
aircraft.add(a);
System.out.println(seatss);
return aircraft.get(a); // err The method get(int) in the type List<Aircraft> is not applicable for the arguments (Aircraft)
}
}
return aircraft;
}
output:
Aircraft: G-AAAAwith model: 737 is a B737 with 192 seats,Statring at: MAN need aleast 4 people.
Aircraft: PH-OFDwith model: 70 is a F70 with 85 seats,Statring at: AMS need aleast 2 people.
Aircraft: PH-EZAwith model: 190 is a E190 with 50 seats,Statring at: BFS need aleast 2 people.
Aircraft: G-AAABwith model: A330 is a A330 with 329 seats,Statring at: LHR need aleast 8 people.
Aircraft: G-AAACwith model: A380 is a A380 with 489 seats,Statring at: DXB need aleast 10 people.
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method get(int) in the type List<Aircraft> is not applicable for the arguments (Aircraft)
at solution.AircraftDAO.findAircraftBySeats(AircraftDAO.java:111)
at solution.Main.main(Main.java:28)
最简单的方法可能是 stream aircraft
列表并filter
它:
public List<Aircraft> findAircraftBySeats(int seats) {
return aircraft.stream()
.filter(a -> a.getSeats() >= seats)
.collect(Collectors.toList());
}
方法List.get(int a)
需要一个 integer ,在您的情况下,您正尝试通过 object 访问它,因此会引发异常。 要获取具有特定座位数的所有飞机的列表,您必须执行以下操作:
public List<Aircraft> findAircraftBySeats(int seats ) {
List<Aircraft> aircraftsWithLimitedSeats = new ArrayList<>();
for (int i = 0; i < aircraft.size(); i++) {
if (aircraft.get(i).getSeats() >= seats) {
aircraftsWithLimitedSeats.add(aircraft.get(i));
}
}
return aircraftsWithLimitedSeats;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.