如何在ArrayList 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 cars = new ArrayList(); cars.add(toyota); cars.add(nissan); cars.add(ford); } public static void processCar(ArrayList cars){ // in heare i need a way of getting the total cost of all three cars by calling // computeCars () System.out.println(cars.get()); }
感谢所有的答案,我应该添加更多的代码。 在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 ); } }
在主要class级
public static void processCar(ArrayList 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? } }
再次感谢
假设您的Car
类具有价格的getter方法,您可以简单地使用
System.out.println (car.get(i).getPrice());
其中i
是元素的索引。
你也可以使用
Car c = car.get(i); System.out.println (c.getPrice());
如果需要存储,还需要从函数中返回totalprice
主要
public static void processCar(ArrayList cars){ int totalAmount=0; for (int i=0; i
并更改函数的return
类型
public int computeCars (){ int totalprice= price+tax; System.out.println (name + "\t" +totalprice+"\t"+year ); return totalprice; }
您没有显示您的Car
,但假设您想要第一辆车的价格,您可以使用:
public static void processCars(ArrayList cars) { Car car = cars.get(0); System.out.println(car.getPrice()); }
请注意,我已将列表的名称从car
更改为cars
– 这是汽车列表 ,而不是一辆汽车。 (我以类似的方式更改了方法名称。)
如果您只希望该方法处理单个汽车,则应将参数更改为Car
类型:
public static void processCar(Car car)
然后像这样调用它:
// In the main method processCar(cars.get(0));
如果你把它留作处理整个列表,那么值得将参数推广到List
– 你不太可能真的要求它是一个ArrayList
。
您应该将列表cars
命名为car
而不是car
,以使其名称与其内容相匹配。
然后你可以简单地说cars.get(0).getPrice()
。 如果你的Car
类还没有这个方法,你需要创建它。
主要class级
public class Test { public static void main (String [] args){ Car thisCar= new Car ("Toyota", "$10000", "2003"); ArrayList car= new ArrayList (); car.add(thisCar); processCar(car); } public static void processCar(ArrayList car){ for(Car c : car){ System.out.println (c.getPrice()); } } }
汽车类
public class Car { private String vehicle; private String price; private String model; public Car(String vehicle, String price, String model){ this.vehicle = vehicle; this.model = model; this.price = price; } public String getVehicle() { return vehicle; } public String getPrice() { return price; } public String getModel() { return model; } }
该列表可能包含多个元素,因此get方法接受一个参数:要检索的元素的索引。 如果你想要第一个,那么它是0。
该列表包含Car实例,因此您只需要这样做
Car firstCar = car.get(0); String price = firstCar.getPrice();
要不就
String price = car.get(0).getPrice();
car
变量应该命名为cars
,因为它是一个列表,因此包含几辆汽车。
阅读有关集合的教程 。 并学习使用javadoc :记录所有类和方法。
如果你想获得所有汽车的价格,你必须遍历数组列表:
public static void processCars(ArrayList cars) { for (Car c : cars) { System.out.println (c.getPrice()); } }