简体   繁体   English

将类添加到 ArrayList 集合

[英]Adding a class to an ArrayList collection

I'm currently working on an assignment where it's asking me to modify my previous method.我目前正在处理一项任务,要求我修改以前的方法。 My current method is:我目前的方法是:

public ParkingTicket issueParkingTicket(ParkedCar car,ParkingMeter meter){
    if(isParkingTimeExpired(car,meter) == true){
        ParkingTicket ticket = new ParkingTicket(getOfficerName(),getBadgeNumber(),car.getLicenseNumber(),car.getCarMake(),car.getCarModel(),calculateFine(car, meter));
        ticket.displayTicketDetails();
        return ticket;
    }
    return null;
}

The collection is a collection of parking tickets (which is also a class "public class ParkingTicket). The method I wrote above resides in a different class (public class ParkingOfficer).该集合是停车票的集合(也是一个类“公共类ParkingTicket”。我上面写的方法驻留在不同的类中(公共类ParkingOfficer)。

This method will create an object.此方法将创建一个对象。 Additionally I'd like this method to create the object and add it to the collection as an ArrayList.此外,我希望使用此方法创建对象并将其作为 ArrayList 添加到集合中。 How would I do that?我该怎么做?

In your other class, do something like this:在您的其他班级中,执行以下操作:

ParkingTicket blah;
ParkingTicket foo;
ParkingTicket bar;

ArrayList<ParkingTicket> allDaTickets = new ArrayList<>();
allDaTickets.add(blah);
allDaTickets.add(foo);
allDaTickets.add(bar);

To Create an ArrayList of a certain class, you do: for example using the class 'Fruit' and calling the list 'fruits'.要创建某个类的 ArrayList,您可以执行以下操作:例如,使用类“Fruit”并调用列表“fruits”。

List<Fruit> fruits = new ArrayList<>();

//to add an instance, to the above list, you use the add method
fruits.add(instance);

In your case, to create a list of ParkingTickets, it would be:在您的情况下,要创建停车票列表,它将是:

List<ParkingTicket> tickets = new ArrayList<>();
tickets.add(ticket); //ticket being an instance of ParkingTicket ofcourse

That being said, you code needs some refactoring.话虽如此,您的代码需要一些重构。 Your if condition should not be:您的 if 条件不应该是:

if(isParkingTimeExpired(car,meter) == true)

I'm assuming isParkingTimeExpired(car, meter) method already returns a boolean, so there is no need for the '==true' part in your condition checking.我假设 isParkingTimeExpired(car, meter) 方法已经返回一个布尔值,所以在你的条件检查中不需要 '==true' 部分。 It would become something like this.它会变成这样。

if(isParkingTimeExpired(car,meter)) { .... }

if the method returns true, it executes the block of the if statement.如果该方法返回 true,则执行 if 语句块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM