我正在尝试从存储在ArrayList中的对象中检索项目。看看代码。
MyList.add(new Car(year,make,available));
现在我已经将一个新的汽车对象存储到myList(arraylist)。我怎样才能获得制作例如?
谢谢。
答案 0 :(得分:1)
您可以使用以下内容遍历列表:
for (Car car : myList)
{
car.getMake(); //if you added getter, if you had not you can use addedCar.make;
}
或者您可以使用项目的索引访问一个特定项目:
Car addedCar = myList.get(0); // 0 because you want the first item.
addedCar.getMake(); //if you added getter, if you had not you can use addedCar.make;
答案 1 :(得分:0)
我的变体:
final Map<Integer, Car> myMap = new HashMap<>();
final Car newCar = new Car(year,make,available);
myMap.put(index, newCar); // where 'index' whatever you want that is unique for this collection year or brand or object ID
// get your object from collection
System.out.println(myMap.get(index)); // output is newCar