java - Hashmap, the values are null -
import java.util.*; public class myhashmap<k,v> extends hashmap<k,v> { public myhashmap(k[] keys, v[] values) { super(); // store <key,value> pairs hashmap object hashmap<string,integer> map = new hashmap<string,integer>(); map.put("hydrogen",1); map.put("lithium",3); map.put("sodium",11); map.put("potassium",19); map.put("rubidium",37); } public string tostring() { return "done"; } public static void main(string[] args) { //two arrays string[] elements ={"hydrogen","lithium","sodium","potassium","rubidium"}; integer[] atomicnumbers = {1,3,11,19,37}; myhashmap<string,integer> map = new myhashmap<string,integer> (elements,atomicnumbers); (int i=0; i<elements.length; i++) { system.out.println("the atomic number of " + elements[i] + " "+ map.get(elements[i])); } system.out.println(map.tostring()); } } the out put wrong (the atomic number of hydrogen null), i`m not sure whether wrong when put key , value or other mistake in code. please help!
remember myhashmap is map, still have populate values. accomplished utilizing arrays have declared in main.
you don't want create object if size of arrays off (or arrays null); leave latter exercise user.
public myhashmap(k[] keys, v[] values) { super(); if (keys.length != values.length) { throw new illegalargumentexception("array lengths not equivalent!"); } // store <key,value> pairs hashmap object (int = 0; < keys.length; i++) { put(keys[i], values[i]); } }
Comments
Post a Comment