
在java中,arraylist的contains(object o)方法用于判断列表中是否包含指定的元素。其核心机制是遍历列表中的每个元素,并使用每个元素的equals()方法与参数o进行比较。如果找到一个元素e使得o.equals(e)返回true,则contains()方法返回true。
然而,当ArrayList中存储的是自定义对象(例如Product对象),而我们尝试使用一个String类型的参数去调用contains()方法时,就会出现问题。一个Product对象永远不会与一个String对象相等(即productInstance.equals(searchString)将始终返回false),因为它们是不同类型的对象。因此,ArrayList.contains(String name)在这种情况下总是返回false,无法实现按产品名称查找的目的。
考虑以下错误示例:
import java.util.*;
class Product {
String name;
int price;
int id;
Product(int i, String name, int price) {
this.id = i;
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "Product{" + "id=" + id + ", name='" + name + '\'' + ", price=" + price + '}';
}
}
public class IncorrectSearchExample {
public static void main(String[] args) {
ArrayList<Product> al = new ArrayList<>();
al.add(new Product(1, "Samsung", 10000));
al.add(new Product(2, "Apple", 20000));
// ... 添加更多产品
Scanner sc = new Scanner(System.in);
System.out.println("请输入要搜索的产品名称:");
String name = sc.nextLine();
// 错误的使用方式:Product对象列表与String参数进行contains比较
if (al.contains(name)) { // 总是返回 false
System.out.println("产品找到");
} else {
System.out.println("产品未找到");
}
sc.close();
}
}上述代码中的if (al.contains(name))行将永远不会找到产品,因为它尝试将一个String对象与ArrayList中的Product对象进行比较,而这两种类型之间不存在equals()意义上的相等性。
要正确地根据对象的某个属性(如产品名称)查找ArrayList中的元素,我们需要手动遍历列表,并在循环内部检查每个对象的相应属性。这可以通过标准的for-each循环实现。
立即学习“Java免费学习笔记(深入)”;
以下示例展示了如何使用传统迭代方式实现精确匹配和模糊匹配(包含):
import java.util.*;
// Product 类定义同上
class Product {
String name;
int price;
int id;
Product(int i, String name, int price) {
this.id = i;
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "Product{" + "id=" + id + ", name='" + name + '\'' + ", price=" + price + '}';
}
}
public class IterativeSearchExample {
public static void main(String[] args) {
ArrayList<Product> al = new ArrayList<>();
al.add(new Product(1, "Samsung", 10000));
al.add(new Product(2, "Apple", 20000));
al.add(new Product(3, "Nokia", 30000));
al.add(new Product(4, "Sony", 40000));
al.add(new Product(5, "LG", 50000));
System.out.println("现有产品列表:");
for (Product p : al) {
System.out.println(p);
}
Scanner sc = new Scanner(System.in);
// --- 精确匹配 ---
System.out.println("\n请输入要搜索的产品名称 (精确匹配,忽略大小写):");
String searchNameExact = sc.nextLine();
Product foundProductExact = null;
for (Product p : al) {
// 使用equalsIgnoreCase()进行不区分大小写的精确匹配
if (p.name.equalsIgnoreCase(searchNameExact)) {
foundProductExact = p;
break; // 找到第一个匹配项后即可退出循环
}
}
if (foundProductExact != null) {
System.out.println("精确匹配产品找到: " + foundProductExact);
} else {
System.out.println("未找到精确匹配产品: " + searchNameExact);
}
// --- 模糊匹配 ---
System.out.println("\n请输入要搜索的产品名称 (模糊匹配,忽略大小写):");
String searchNamePartial = sc.nextLine();
List<Product> foundProductsPartial = new ArrayList<>();
for (Product p : al) {
// 将产品名称和搜索词都转换为小写,然后使用contains()进行模糊匹配
if (p.name.toLowerCase().contains(searchNamePartial.toLowerCase())) {
foundProductsPartial.add(p);
}
}
if (!foundProductsPartial.isEmpty()) {
System.out.println("模糊匹配产品找到:");
for (Product p : foundProductsPartial) {
System.out.println(p);
}
} else {
System.out.println("未找到模糊匹配产品: " + searchNamePartial);
}
sc.close();
}
}注意事项:
Java 8引入的Stream API提供了一种更声明式、更简洁的方式来处理集合数据。它特别适合进行过滤、映射和查找等操作。
import java.util.*;
import java.util.stream.Collectors;
// Product 类定义同上
class Product {
String name;
int price;
int id;
Product(int i, String name, int price) {
this.id = i;
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "Product{" + "id=" + id + ", name='" + name + '\'' + ", price=" + price + '}';
}
}
public class StreamSearchExample {
public static void main(String[] args) {
ArrayList<Product> al = new ArrayList<>();
al.add(new Product(1, "Samsung", 10000));
al.add(new Product(2, "Apple", 20000));
al.add(new Product(3, "Nokia", 30000));
al.add(new Product(4, "Sony", 40000));
al.add(new Product(5, "LG", 50000));
System.out.println("现有产品列表:");
al.forEach(System.out::println); // 使用Stream API打印
Scanner sc = new Scanner(System.in);
// --- Stream API 精确匹配第一个元素 ---
System.out.println("\n请输入要搜索的产品名称 (Stream 精确匹配,忽略大小写):");
String streamSearchExact = sc.nextLine();
Optional<Product> streamFoundExact = al.stream()
.filter(p -> p.name.equalsIgnoreCase(streamSearchExact)) // 过滤出匹配的元素
.findFirst(); // 获取第一个匹配的元素,返回Optional
streamFoundExact.ifPresentOrElse(
p -> System.out.println("Stream 精确匹配产品找到: " + p),
() -> System.out.println("Stream 未找到精确匹配产品: " + streamSearchExact)
);
// --- Stream API 模糊匹配所有元素 ---
System.out.println("\n请输入要搜索的产品名称 (Stream 模糊匹配,忽略大小写):");
String streamSearchPartial = sc.nextLine();
List<Product> streamFoundPartial = al.stream()
.filter(p -> p.name.toLowerCase().contains(streamSearchPartial.toLowerCase()))
.collect(Collectors.toList()); // 将所有匹配的元素收集到新列表中
if (!streamFoundPartial.isEmpty()) {
System.out.println("Stream 模糊匹配产品找到:");
streamFoundPartial.forEach(System.out::println);
} else {
System.out.println("Stream 未找到模糊匹配产品: " + streamSearchPartial);
}
sc.close();
}
}Stream API 优势:
在选择查找方法时,除了代码的简洁性,性能也是一个重要的考量因素。
选择合适的匹配方式:
数据结构选择与性能优化:
以下是如何使用HashMap进行快速查找的示例:
import java.util.*;
// Product 类定义同上
class Product {
String name;
int price;
int id;
Product(int i, String name, int price) {
this.id = i;
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "Product{" + "id=" + id + ", name='" + name + '\'' + ", price=" + price + '}';
}
}
public class HashMapSearchExample {
public static void main(String[] args) {
ArrayList<Product> al = new ArrayList<>();
al.add(new Product(1, "Samsung", 10000));
al.add(new Product(2, "Apple", 20000));
al.add(new Product(3, "Nokia", 30000));
al.add(new Product(4, "Sony", 40000));
al.add(new Product(5, "LG", 50000));
// 将 ArrayList 转换为 HashMap 便于快速查找
// 键为产品名称(转换为小写以支持不区分大小写查找),值为产品对象
Map<String, Product> productMap = new HashMap<>();
for (Product p : al) {
// 假设产品名称是唯一的,或者我们只关心第一个同名产品
productMap.put(p.name.toLowerCase(), p);
}
// 如果产品名称不唯一,且需要存储所有同名产品,则需要 Map<String, List<Product>>
System.out.println("现有产品列表 (通过HashMap展示):");
productMap.以上就是Java ArrayList中按对象属性查找元素的正确姿势的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号