首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >hashmap中的hashmap?

hashmap中的hashmap?
EN

Stack Overflow用户
提问于 2017-01-21 21:15:45
回答 2查看 573关注 0票数 0

我有一个可扩展的列表视图,对于每个孩子,我需要有4个“附加”或字符串或任何名称:- link1 - link2。

后面是一个教程,创建列表视图、不同的父级和仅使用一个字符串的子元素都没有问题。我曾经尝试在hashmap中创建一个hashmap,但是它没有很好地工作。什么是更好的解决方案?

代码语言:javascript
复制
public void filldata(){

    ArrayList productinfo = new ArrayList<>();
    categories = new HashMap<>();
    topics = new HashMap<>();


    categories.add("FITNESS"); //This would be the parent title
    categories.add("MONEY");

    List<String> Fitness=new ArrayList<>();
    List<String> Money=new ArrayList<>();


    Fitness.add("Product1"); // this would be child1
    List<String> Product1=new ArrayList<>();
    Product1.add("desc1"); //this would be the description of child 1
    Product1.add("link1.1");//this would be the link1 of child 1
    Product1.add("link1.2");//this would be the link2 of child 1


    Fitness.add("Product2"); //child2
    Fitness.add("Product3"); //child3

    Money.add("Product1"); //child 1
    Money.add("Product2"); //   "  2
    Money.add("Product3"); //   "  3

    topics.put(categories.put(productinfo.get(0),Fitness)); //doesn't seem to work like this
    categories.put(productinfo.get(1),Money);

}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-01-21 21:35:02

只需创建一个类来保存所有这些信息。

代码语言:javascript
复制
public class Child {

String title;
String description;
String link1;
String link2;

}

现在您有了一个类,您可以在listview中创建这个类的许多实例,并将它们全部添加到一个数组列表中,并将其传递给您的ListAdapter。例如,

代码语言:javascript
复制
Child firstChild = new Child();
firstChild.title = "First Child";
firstChild.description = "Description 1";
firstChild.link1 = "link1";
firstChild.link2 = "link2";

List<Child> childList = new ArrayList<>();
childList.add(firstChild);

可以向此列表中添加任意数量的子对象,然后将此列表传递给ListAdapter。

票数 2
EN

Stack Overflow用户

发布于 2017-01-21 22:03:13

hashmap中的hashmap?

是。

HashMap将键与值关联。键可以是任何正确实现o.equals(Object otherObject)o.hashCode()方法的不可变的Object,而值可以是任何Object

HashMap通常不是不可变的,所以您可能不想使用HashMap对象作为键,但是您绝对可以使用HashMap对象作为值。

Topics.put(categories.put(.);//似乎不起作用

您没有说明为什么不起作用,但我猜您无法让它编译。原因是,您试图使用一个参数来调用topics.put(...) -- categories.put(...)返回的值。但是,HashMap put(...)方法需要两个参数:键和值。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41784596

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档