Java的哈希映射值阵列 [英] Java Hashmap values to Array

查看:113
本文介绍了Java的哈希映射值阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code它增加了一些阵列一个HashMap但后来我想访问这些阵列后来做对他们的一些工作。到目前为止,我已经得到了这一点,但想不通其余出来,使其工作......

 进口的java.util.HashMap;
进口java.util.Iterator的;
进口java.util.Map.Entry;    公共静态无效的主要(字串[] args){        的String [] [] = layer1的{
            {TO1,TYPE1,开始},
            {TO2,类型1,开始}
        };        的String [] [] = 2层{
            {TO3,TYPE2,ITEM1},
            {TO3,TYPE2,ITEM2}
        };        HashMap的<弦乐,对象> HashMap的=新的HashMap<弦乐,对象>();
        hashMap.put(layer1的,层1);
        hashMap.put(二层,二层);        迭代器<钥匙进入LT;弦乐,对象>> 。迭代= hashMap.entrySet()迭代();
        而(iterator.hasNext()){
            。hashMap.values​​()的toArray();
            对于(???){
                //这里可以打印阵列例如
            }
        }    }


解决方案

气味像功课,但也有少数的建议 -


  • 没有理由为你的Hashmap是形式<弦乐,对象> - 使其<字符串,字符串[] [ ]方式> ,因为这是你存储什么

您正在迭代的两倍。你要么
- 遍历地图,无论是键,值或条目。每个项目都是一个迭代器的返回值,例如

 为(字符串[] [] S:map.values​​()){
 ...
}


  • hashmap.values​​.toArray给你所有的内容,这是你的迭代器做同样的事情。


  • 如果你只通过迭代的内容,那么你就没有真正使用的地图,因为你永远利用的事实,你的值可通过按键。


I have the following code which adds some arrays to a hashmap but then I want access those arrays to do some work on them later. I've gotten this far but can't figure the rest out to make it work....

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

    public static void main(String[] args) {

        String[][] layer1 = {
            {"to1", "TYPE1", "start"}, 
            {"to2", "TYPE1", "start"}
        };

        String[][] layer2 = {
            {"to3", "TYPE2" ,"item1"},
            {"to3", "TYPE2" ,"item2"}
        };

        HashMap<String,Object> hashMap = new HashMap<String,Object>();
        hashMap.put("layer1", layer1);
        hashMap.put("layer2", layer2);

        Iterator<Entry<String, Object>> iterator = hashMap.entrySet().iterator();
        while(iterator.hasNext()){
            hashMap.values().toArray();
            for (???) {
                // lets print array here for example
            }
        }        

    }

解决方案

Smells like homework, but a few suggestions -

  • there's no reason for your Hashmap to be of the form <String,Object> - make it <String, String[][]> , as that's what you're storing.

You're iterating twice. You either - iterate through the map, either the keys, values or entries. Each item is an iterator return value, e.g.

for (String[][] s:map.values()){
 ...
}

  • hashmap.values.toArray gives you all of the contents, which is the same thing your iterator is doing.

  • if you're only iterating through the contents, then you're not really using a map, as you're never making use of the fact that your values are available by key.

这篇关于Java的哈希映射值阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆