如果在ArrayList中找不到特定对象的值,可以使用以下方法来解决问题:
ArrayList list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");
String searchItem = "Banana";
if (list.contains(searchItem)) {
int index = list.indexOf(searchItem);
String value = list.get(index);
System.out.println("Found value: " + value);
} else {
System.out.println("Value not found in the list.");
}
class Fruit {
private String name;
public Fruit(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Fruit fruit = (Fruit) obj;
return Objects.equals(name, fruit.name);
}
}
ArrayList fruits = new ArrayList<>();
fruits.add(new Fruit("Apple"));
fruits.add(new Fruit("Banana"));
fruits.add(new Fruit("Orange"));
Fruit searchItem = new Fruit("Banana");
if (fruits.contains(searchItem)) {
int index = fruits.indexOf(searchItem);
Fruit foundFruit = fruits.get(index);
System.out.println("Found fruit: " + foundFruit.getName());
} else {
System.out.println("Fruit not found in the list.");
}
使用上述方法之一,您可以找到ArrayList中特定对象的值。