英文:
ArrayList from class objects simpler way to do?
问题
我知道如何将类对象放入 Java 的 ArrayList
中(因为新对象可以附加而无需首先知道索引),但我想知道是否有一种更简单的方法将它们添加到 ArrayList
并对它们进行迭代?
我甚至在思考,假设我将对象名称保持在某种模式中,我应该能够使用循环将每个对象添加到列表中,例如 car1, car2, car3, ...
import java.util.ArrayList;
public class TestCar {
public static void main(String[] args) {
ArrayList<String> carNames = new ArrayList<>();
// Cars have simple getter methods corresponding with String and int
Car car1 = new Car("Rav4", 2017);
carNames.add(car1.getName());
Car car2 = new Car("Commodore", 2005);
carNames.add(car2.getName());
for (int i = 0; i < carNames.size(); i++) {
System.out.println(carNames.get(i));
}
}
}
一如既往,感谢任何回复!
英文:
I know how to put class objects to an ArrayList
in java (since new objects can be appended without knowledge of an index first) but I was wondering if there is a simpler way of adding them to an ArrayList
and iterating over them?
I was even thinking that, hypothetically, if I kept my object names in a pattern, that I should be able to add each object to the list using a loop e.g. car1, car2, car3, ...
import java.util.ArrayList;
public class TestCar {
public static void main(String[] args) {
ArrayList<String> carNames = new ArrayList<>();
// Cars have simple getter methods corresponding with String and int
Car car1 = new Car("Rav4", 2017);
carNames.add(car1.getName());
Car car2 = new Car("Commodore", 2005);
carNames.add(car2.getName());
for (int i = 0; i < carNames.size(); i++) {
System.out.println(carNames.get(i));
}
}
}
As always, thanks for any replies!
答案1
得分: 1
假设您正在使用Java 8或更高版本,您可以将您的Car
对象添加到一个列表中,并使用流来获取carNames
列表:
List<Car> myCarList = Arrays.asList(new Car("Rav4", 2017), new Car("Commodore", 2005));
List<String> carNames = myCarList.stream()
.map(Car::getName)
.collect(Collectors.toList());
英文:
Assuming you are using Java 8 or higher, you could add your Car
objects to a list and use streams to get a list of carNames
:
List<Car> myCarList = Arrays.asList( new Car("Rav4", 2017), new Car("Commodore", 2005));
List<String> carNames = myCarList.stream()
.map(Car::getName)
.collect(Collectors.toList());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论