2012-04-19 55 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

相关问题