简体   繁体   中英

How to use ArrayList in Java

I have 3 classes ( Car (superclass), CarToRent , and CarToSell (extend Car).

I'm making an interface (CarCompany) and want to store an ArrayList of type car in it. How do I do this? Please help?

In an interface, you can't set attributes because all of them have the final modifier by default, so just declare the get and set method for your interface. Let that the implementors have the attribute and overrides those methods.

public interface CarCompany {
    List<? extends Car> getCarList();
    void setCarList(List<? extends Car> carList);
}

UPDATE:

First, you shouldn't use ArrayList even if you can, instead use List interface, ArrayList implements that interface (more info about this: What does it mean to "program to an interface"? ):

List<Car> carList = new ArrayList<Car>();

Second, if you have a superclass, the list attribute shouldn't be for the superclass, instead for a template that supports all that class generation. Let's see a sample of this: you have a DAO class that returns a List<CarToRent> and a List<CarToSell> in different methods. Later on, in a business class, you need to read all the elements for a List<Car> and use the price of the car for some formula. Will you create a method to convert from List<CarToRent> to List<Car> and one for List<CarToSell> to List<Car> , what if later on you need to create a new child of Car like WreckedCar for a CarWorkshop , will you create a third converter? So, instead of all that pain, you can use the List<? extends Car> List<? extends Car> that do that "dirty work" for you:

public void executeSomeFormula(List<? extends Car> carList) {
    //getting the actual VAT value (just for a sample);
    double actualVAT = getActualVATValue();
    //every object in the list extends Car, so it can be threatened as a Car instance
    for(Car car : carList) {
        car.setTotalPrice(car.getPrice() * (1 + actualVAT));
    }
}

您应该创建一个ArrayList<CarCompany> ,以便能够存储来自实现CarCompany接口的类的每种对象。

import java.util.ArrayList;

ArrayList<TYPE> al = new ArrayList<TYPE>();
so if you need CarCompany
eg.
ArrayList<CarCompany> al = new ArrayList<CarCompany>();

Also have a look at this document about Class ArrayList

Your interface should not have a List of cars. It may define getter and setting methods for the List but should not define it. Your concrete classes that implement your interface should define the List .

public class CarCompany{
    private List<Car> myList = new ArrayList<Car>();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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