【发布时间】:2015-04-23 09:58:25
【问题描述】:
我有一个未排序的对象列表。每个对象都包含一个唯一的搜索关键字。下面是一些示例代码:
import java.util.*;
class Dog {
private final String nameKey;
private final String owner;
private final int age;
private final int weight;
Dog(String n, String o, int a, int w) {
nameKey = n;
owner = o;
age = a;
weight = w;
}
String getName() {
return nameKey;
}
String getOwner() {
return owner;
}
int getAge() {
return age;
}
int getWeight() {
return weight;
}
}
public class SearchThoughList {
public static void main(String[] args) {
List<Dog> dogList = new ArrayList<>();
int i=0;
String searchString;
dogList.add(new Dog("squire", "tom:", 10, 40));
dogList.add(new Dog("lucy","tom", 5, 37));
dogList.add(new Dog("gretta", "bob", 12, 22));
dogList.add(new Dog("lassie", "timmy", 7, 55));
dogList.add(new Dog("bailey", "bob", 5, 100));
searchString = "lassie";
// Here's where I need help
// i = SomeClass.searchMethod(dogList, searchString);
//
System.out.println(searchString+" is at index: "+i);
}
}
问题 1: 搜索列表并找到其键等于搜索值的元素的好方法是什么?显然,由于列表未排序,我需要遍历整个内容,直到找到关键。我可以编写代码来做到这一点。但是,作为 Java 和 OOP 的新手,我想知道是否已经存在执行此操作的类/方法——更符合 OOP 范式的精神。
问题 2: 假设列表已排序,是否存在比 ArrayList 更好的结构?然后我假设存在可以使用二进制搜索的类/方法?
提前致谢。
【问题讨论】: