簡體   English   中英

返回數組列表中的列表 object java

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM