返回数组列表对象java中的列表

3pvhb19x  于 2021-06-27  发布在  Java
关注(0)|答案(2)|浏览(349)

我试图返回一个具有指定座位数的对象列表。我的 ArrayList 有所有的对象,我想在一个条件下返回所有的对象。它处理系统输出,但不返回列表。我要返回至少329个座位的不同对象。

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;
}

输出:

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)
jckbn6z7

jckbn6z71#

最简单的方法可能是流式传输 aircraft 列表和 filter 信息技术:

public List<Aircraft> findAircraftBySeats(int seats) {
    return aircraft.stream()
                   .filter(a -> a.getSeats() >= seats)
                   .collect(Collectors.toList());
}
ecbunoof

ecbunoof2#

方法 List.get(int a) 需要一个整数,在您的情况下,您试图通过一个对象访问它,因此会引发一个异常。要获得具有特定座位数的所有飞机的列表,您必须执行以下操作:

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;
}

相关问题