2013-08-17 42 views
1

我用ArrayList我的字典索引數據的Android的ListView ArrayList的相似搜索

我想做出類似的搜索系統

例如

dictionary data : 'abcd' 'bcde' 'cdef' 'fghi' 'ijkl' 

如果我搜索'cd'我想index '3'

我的源代碼

for (String st : wordList) { 
    if (st.indexOf(searchWord) == 0) { 
     ListView.setSelection(index); //set listView scroll 
     break; 
    } 
    index++; 
} 

但我花了太多的時間:(

是什麼使這個系統的最佳方法是什麼?

回答

0

分而治之 :)

而不是存儲所有字典數據成單個列表....對於每個字符像創建數組列表,B,C,d(你將有總26清單:一個是每個字母)

Map<Character, List<String>> map = new HashMap<Character, List<String>>(); 

// creating list for each char 
for(int i=0;i<26;i++){ 
    char ch = (char) ('a' + i); 
    map.put(ch,new ArrayList<String>()); 
} 

// storing some sample dictionary data or make a function for it 
map.get("abcd".charAt(0)).add("abcd"); 
map.get("bcde".charAt(0)).add("bcde"); 
map.get("cdef".charAt(0)).add("cdef"); 
map.get("fghi".charAt(0)).add("fghi"); 
map.get("ijkl".charAt(0)).add("ijkl"); 

String searchWord = "cd"; 

// searh the given String 
List<String> wordList =map.get(searchWord.charAt(0)); 
int idx =0; 

for (String st : wordList) { 
    if (st.startsWith(searchWord)) { 
     idx = wordList.indexOf(st); 
     System.out.println("position="+idx); //display index in log 

     break; 
     } 
    } 

    // if require, In idx variable : add the size() of all list 
     // which come before the give searh char 
    // ListView.setSelection(idx); //set listView scroll 

}

注意:請轉換在搜索或存儲之前將大寫字母縮寫爲小寫字母。

+0

請參閱此鏈接,以及 的http://計算器.com/questions/2000237/in-java-which-most-recommended-class-class-for-a-dictionary-data-structure –

+0

哦,這真的很有幫助謝謝 – user2637015

1

只是從循環中刪除索引++,如果(CONDITION)如此,則更改。

for (String st : wordList) { 
    if (st.startsWith(searchWord)) { 
     System.out.println("position="+wordlist.indexOf(st));//display index in log 
     ListView.setSelection(wordlist.indexOf(st)); //set listView scroll 
     break; 
     } 
    } 
+0

如果刪除索引++它不工作我無法理解你的答案 – user2637015

+0

我剛編輯我的答案,請嘗試.. –

+0

感謝startWith比的indexOf更好:) – user2637015