如何在ArrayList java中获取值

bla*_*tar 12 java

我试图从ArrayList中获取值.以下是我的代码示例:

public static void main (String [] args){
    Car toyota= new Car("Toyota", "$10000", "300"+ "2003");
    Car nissan= new Car("Nissan", "$22000", "300"+ "2011");
    Car ford= new Car("Ford", "$15000", "350"+ "2010");

    ArrayList<Car> cars = new ArrayList<Car>();
    cars.add(toyota);        
    cars.add(nissan);
    cars.add(ford);
}

public static void processCar(ArrayList<Car> cars){

   // in heare i need a way of getting the total cost of all three cars by calling 
    //  computeCars ()
    System.out.println(cars.get());
}
Run Code Online (Sandbox Code Playgroud)

感谢所有的答案,我应该添加更多的代码.在Car类中,我有另一种计算总成本的方法,包括税收.

class Car {
    public Car (String name, int price, int, tax, int year){
        constructor.......
    }

    public void computeCars (){
        int  totalprice= price+tax;
        System.out.println (name + "\t" +totalprice+"\t"+year );
     } 
}
Run Code Online (Sandbox Code Playgroud)

在主要班级

public static void processCar(ArrayList<Car> cars){
    int totalAmount=0;
    for (int i=0; i<cars.size(); i++){
        cars.get(i).computeCars ();
        totalAmount=+ ?? // in need to add the computed values of totalprice from the  Car class?
    }
}
Run Code Online (Sandbox Code Playgroud)

再次感谢

Ank*_*kur 14

假设你的Car班级有一个价格的getter方法,你可以简单地使用

System.out.println (car.get(i).getPrice());
Run Code Online (Sandbox Code Playgroud)

where i是元素的索引.

你也可以使用

Car c = car.get(i);
System.out.println (c.getPrice());
Run Code Online (Sandbox Code Playgroud)

totalprice如果需要存储,还需要从函数返回

主要

public static void processCar(ArrayList<Car> cars){
    int totalAmount=0;
    for (int i=0; i<cars.size(); i++){
        int totalprice= cars.get(i).computeCars ();
        totalAmount=+ totalprice; 
    }
}
Run Code Online (Sandbox Code Playgroud)

并更改return您的功能类型

public int computeCars (){
    int  totalprice= price+tax;
    System.out.println (name + "\t" +totalprice+"\t"+year );
    return  totalprice; 
 }
Run Code Online (Sandbox Code Playgroud)