我对linked-list
提出了疑问。您如何搜索看起来像这样的内容并找到string
"Freda"
?
private LinkedList<Boat> boats = new LinkedList<Boat>();
boats.add(new Boat(1, "Ed", 3));
boats.add(new Boat(2, "Fred", 7));
boats.add(new Boat(3, "Freda", 5));
答案 0 :(得分:0)
我假设,getName是将返回船名的getter。
for(int i=0;i<boats.size();i++){
if(searchedWord.equals(boats.get(i).getName()){
//do your operation here
}
}
答案 1 :(得分:0)
迭代您的列表,然后搜索您的值
for(Boat a: boats){
if(a.name.equals("Freda")){ // name is the variable you have used to store "Fread"
// sout("Found");
break;
}
}
答案 2 :(得分:0)
假设你的船上有吸气剂和固定剂:
public Boat search (LinkedList<Boat> list, String searchedName) {
for (Boat boat : list) {
if(boat.getName().equals(searchedName) {
return boat;
}
}
throw new IllegalArgumentExcetion("This boat was not found");
}
答案 3 :(得分:0)
已添加评论您应该选择Map<Key,Value> Pair Approach
private Map<String,Boat> boats = new HashMap<String,Boat>();
boats.put("ED",new Boat(1, "Ed", 3));
boats.put("Fred",new Boat(2, "Fred", 5));
boats.put("Ted",new Boat(3, "Ted", 8));
然后,当您想要搜索时,您可以始终这样做:
boats.get("Fred");
答案 4 :(得分:0)
如果要搜索内容,则需要使用像Data Store这样的索引集合: https://github.com/jparams/data-store
示例:
error C2100: illegal indirection
使用数据存储,您可以创建不区分大小写的索引和各种很酷的东西。如果你正在进行大量的查找,你肯定想要使用像这样的库来循环。
答案 5 :(得分:0)
您可以通过过滤列表流轻松解决问题;
final List<Boat> ed = boats.stream().filter(boat -> boat.name.equals("Ed")).collect(Collectors.toList());
这将返回名称为Ed