我的Arraylist包含9个人。每个人都有一个 String 类型的 name 值、一个 int 类型的age 值和一个 Enum 类型的值(TV、SMARTPHONE、CAR)。我必须创建实现一个根据产品名称查找名称的方法。 如果 arrayListName 包含 SMARTPHONE,则返回所有带有智能手机的名称。
public void showByProduct(Product SMARTPHONE) {
public void showByProductName(Product SMARTPHONE) {
if (arrayListName.contains(SMARTPHONE))
System.out.println("found"+nameofowner);
else {
System.out.println("not found");
}
}
最佳答案
您需要迭代您的List
,并对于每个人,检查其product
字段是否具有您在方法中传递的值。
此外,您的方法还需要一个本地List
,您可以在其中添加与产品名称
匹配的Person
>,然后最后返回该 List
。
public List<Person> showByProductName(Product product) {
List<Person> localList = new ArrayList<Person>();
for (Person person: persons) { // persons is the original List.
if (person.getProduct() == product) {
localList.add(person);
}
}
return localList;
}
在调用此方法的地方,将返回值存储在 List
引用中: -
List<Person> result = showByProductName(Product.SMARTPHONE);
System.out.println(result);
请注意,您可以使用 ==
比较两个 enum
值。因为 enum
是一个 singleton
。
P.S: - 您的参数名称不要为 SMARTPHONE
。这是一个枚举值。另外,根据Java命名约定,变量名称应以小写字母开头,并遵循camelCasing
。
关于java - 数组列表。按产品类型按文章访问名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14402691/