Java: how to convert HashMap to array

前端 未结 12 1933
时光取名叫无心
时光取名叫无心 2020-11-29 16:36

I need to convert a HashMap to an array; could anyone show me how it\'s done?

12条回答
  •  粉色の甜心
    2020-11-29 17:01

    @SuppressWarnings("unchecked")
        public static  E[] hashMapKeysToArray(HashMap map)
        {
            int s;
            if(map == null || (s = map.size())<1)
                return null;
    
            E[] temp;
            E typeHelper;
            try
            {
                Iterator> iterator = map.entrySet().iterator();
                Entry iK = iterator.next();
                typeHelper = iK.getKey();
    
                Object o = Array.newInstance(typeHelper.getClass(), s);
                temp = (E[]) o;
    
                int index = 0;
                for (Map.Entry mapEntry : map.entrySet())
                {
                    temp[index++] = mapEntry.getKey();
                }
            }
            catch (Exception e)
            {
                return null;
            }
            return temp;
        }
    //--------------------------------------------------------
        @SuppressWarnings("unchecked")
        public static  T[] hashMapValuesToArray(HashMap map)
        {
            int s;
            if(map == null || (s = map.size())<1)
                return null;
    
            T[] temp;
            T typeHelper;
            try
            {
                Iterator> iterator = map.entrySet().iterator();
                Entry iK = iterator.next();
                typeHelper = iK.getValue();
    
                Object o = Array.newInstance(typeHelper.getClass(), s);
                temp = (T[]) o;
    
                int index = 0;
                for (Map.Entry mapEntry : map.entrySet())
                {
                    temp[index++] = mapEntry.getValue();
                }
            }
            catch (Exception e)
            {return null;}
    
            return temp;
        }
    

提交回复
热议问题