2012-04-19 53 views
0

我正在取出由sqlite的數據在android系統是如下提取的數據轉換成字符串,字符串數組地圖

URL      PHONE 
--------------------------------- 
/test/img1.png   98989898 
/test/img1.png   61216121 
/test/img2.png   75757575 
/test/img2.png   40404040 
/test/img3.png   36363636 

現在我想創建這樣的地圖存儲的數據如下

/test/img1.png   [98989898 , 61216121 ] 
    /test/img2.png   [75757575 , 40404040 ] 
    /test/img3.png   [36363636] 

這樣我就可以將整個地圖傳遞給函數,最終在後臺函數中獲取圖像url並將數據發送到電話號碼列出的數組。所以我怎麼能將我已經獲取的數據轉換成字符串數組樣式的關鍵字?

回答

4

我會創建一個Map<String, List<String>>(又名「多圖」)。如果您使用List<String>,則在開始之前,您無需知道給定URL的電話號碼。如果你選擇數組路由,情況並非如此。

Map<String, List<String>> results = new HashMap<String, List<String>>(); 
while (rs.next()) { 
    String url = rs.getString(1); 
    String phone = rs.getString(2); 
    List<String> phones = (results.contains(url) ? results.get(url) : new ArrayList<String>()); 
    phones.add(phone); 
    results.put(url, phones); 
} 

Google Collections有一個可以直接使用的多圖,但我認爲您會同意這樣做。

如果你想存儲更多的項目(例如名稱),你應該開始思考一個對象,它們將所有這些項目集中在一起成爲一個連貫的東西。 Java是一種面向對象的語言。你聽起來像你犯的思想太低了。字符串,基元和數據結構是對象的構建塊。也許你需要一個人在這裏:

package model; 

public class Person { 
    private String name; 
    private Map<String, List<String>> contacts; 

    // need constructors and other methods. This one is key 
    public void addPhone(String url, String phone) { 
     List<String> phones = (this.contacts.contains(url) ? this.contacts.get(url) : new ArrayList<String>()); 
     phones.add(phone); 
     this.contacts.put(url, phones); 
    } 
} 

我會離開你休息。

如果你這樣做,你需要將結果集映射到Person中。但是你應該從我發佈的代碼中看到這個想法。

+0

如果我想存儲名稱字段呢?名稱的網址[電話1,電話2]? – Hunt 2012-04-19 11:19:56

相關問題