【问题标题】:How to get content of HashMap and displat it on Android?如何获取 HashMap 的内容并在 Android 上显示?
【发布时间】:2011-11-03 12:37:14
【问题描述】:

我有这个:

HashMap<String, String[]> strs = new HashMap<String, String[]>(); 
String [] morning_food = new String [8];
String [] snack1_food = new String [6];
String [] lunch_food = new String [12];
String [] snack2_food = new String [4];
String [] nite_food = new String [10];

strs.put("Breakfast", morning_food);
strs.put("Snack1", snack1_food);
strs.put("Lunch", lunch_food);
strs.put("Snack2", snack2_food);
strs.put("Dinner", nite_food);

如何获取strs的内容?我想打印出来或显示到日志中。谢谢

【问题讨论】:

  • 我看到这个问题缺乏研究,因为来自HashMap的数据可以用一个key来检索,这是put方法的第一个参数,你使用get方法和key值来检索数据...
  • 我的是String [],对象是数组,不同的问题应该是>_

标签: java android arrays hashmap


【解决方案1】:

strs.toString()?

你可以:

for (String[] vals : strs.values()) {
    for (String val : vals) {
        System.out.print(val);
    }
}

【讨论】:

  • 两者都没有显示String [] Morning_food = new String [8]的内容;字符串 [] 零食 1_food = 新字符串 [6];字符串 [] 午餐食物 = 新字符串 [12];字符串 [] 零食 2_food = 新字符串 [4];字符串 [] nite_food = 新字符串 [10];
【解决方案2】:

strs.toString() 将地图的内容作为字符串返回。它将委托给数组的默认toString,但不会打印任何有用的东西。所以你应该使用 List 而不是 String[] 作为 map 的值类型:

Map<String, List<String>> strs = new HashMap<String, List<String>>(); 
strs.put("Breakfast", new ArrayList<String>());
...

在大多数情况下,集合通常应优先于数组。

【讨论】:

  • 所以我应该把这个 String [] morning_food = new String [8];字符串 [] 零食 1_food = 新字符串 [6];字符串 [] 午餐食物 = 新字符串 [12];字符串 [] 零食 2_food = 新字符串 [4];字符串 [] nite_food = 新字符串 [10];所以他们是相关的?
  • 你不要把它放在任何地方。列表具有动态大小。一旦你添加了一些东西,它的大小将自动增加。阅读 javadoc:这是一个必须知道的核心类。
【解决方案3】:
String[] str-new String[strs.size()];
Set set=strs.keySet();
for(int i=0;i<strs.size();i++){
str[i]=strs.get(set.get(i));
}

这里的str数组将包含所有的值。否则你可以直接使用strs.get(set.get(i))

【讨论】:

    猜你喜欢
    • 2011-12-22
    • 2012-07-15
    • 2021-08-18
    • 2015-10-09
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 2015-06-08
    • 2015-06-13
    相关资源
    最近更新 更多