請參閱上面的@oxbow_lakes - 我想你想要的是不要通過String
作爲whatSearch
,它是傳遞一小段代碼知道如何獲得你感興趣的屬性。對於一般較小版本:
public static interface PlaneMatcher {
boolean matches(Plane plane, String query);
}
public int search(PlaneMatcher matcher, String query){
int place = -1;
boolean found = false;
for (Iterator<Plane> iteraPlane = this.planes.iterator(); iteraPlane.hasNext() && found == false;) {
Plane temp = (Plane) iteraPlane.next();
if (matcher.matches(temp, query) {
found = true;
}
place++;
}
return place;
}
...
// example
int pilotNameIndex = search(new PlaneMatcher() {
boolean matches(Plane plane, String query) {
// note: assumes query non-null; you probably want to check that earlier
return query.equals(plane.getPilotName());
}
}, "Orville Wright");
(順便說一下,如果它的索引你有興趣,而不是Plane
本身,我不會與一個Iterator
費心 - 只需使用一個老式的for (int i = 0; i < planes.size(); i++)
循環,當你有匹配時,return i
。)
現在,棘手的一點是,如果你在搜索的時候真的被任意字符串在運行時識別出來。如果是這樣的話,我可以建議兩種選擇:
- 這些值不存儲爲對象字段 -
plane.pilotName
,plane.destination
- 在所有。只需要有一個Map<String, String>
(或更好的Map<Field, String>
,其中Field
是所有有效字段的Enum
)稱爲類似plane.metadata
。
- 將它們存儲爲對象字段,但是如上所述預先填充字段名稱到
PlaneMatcher
實例的映射。
例如:
private static final Map<String, PlaneMatcher> MATCHERS = Collections.unmodifiableMap(new HashMap<String, PlaneMatcher>() {{
put("pilotName", new PlaneMatcher() {
boolean matches(Plane plane, String query) {
return query.equals(plane.getPilotName());
});
...
put("destination", new PlaneMatcher() {
boolean matches(Plane plane, String query) {
return query.equals(plane.getDestination());
});
}}
...
public int search(String whatSearch, String query){
PlaneMatcher matcher = MATCHERS.get(whatSearch);
int place = -1;
boolean found = false;
for (Iterator<Plane> iteraPlane = this.planes.iterator(); iteraPlane.hasNext() && found == false;) {
Plane temp = (Plane) iteraPlane.next();
if (matcher.matches(temp, query) {
found = true;
}
place++;
}
return place;
}
哦,你可能會使用反射。別。 :)
你可以發佈你試過的代碼嗎? – Cogsy 2009-06-28 20:47:56
我認爲這裏的關鍵詞是* random *屬性。我已經在下面發佈了一個答案,因爲我認爲你正在詢問如何實現一種算法,該算法在編碼算法的過程中搜索某些你不知道正在搜索的內容*。如果你不問這個問題,那麼我建議你改進你的問題,使其更清晰。 – 2009-06-28 21:26:27