本帖最后由 王宝龙 于 2012-9-19 22:22 编辑
为什么我把定义的HashMap封装在类中(第一种)编译就失败呢?
而如果放在主函数下里面就可以呢?这是哪里有问题?
第一种:
- import java.util.*;
- class MyMap
- {
- HashMap<Integer,String> hm = new HashMap<Integer,String>();
- hm.put(1,"abcd");
- hm.put(2,"abc");
- hm.put(3,"def");
- hm.put(4,"ghi");
- hm.put(5,"jkl");
- hm.put(6,"mno");
- hm.put(7,"pqrs");
- hm.put(8,"tuv");
- hm.put(9,"wxyz");
-
- public HashMap<Integer,String> getHm()
- {
- return hm;
- }
- }
- class Second
- {
- public static void main(String[] arge)
- {
-
- for(int i=1;i<10;i++)
- sop(new MyMap.getHm().get(i));
- }
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- }
复制代码 第二种:- import java.util.*;
- class Second
- {
- public static void main(String[] arge)
- {
- HashMap<Integer,String> hm = new HashMap<Integer,String>();
- hm.put(1,"abcd");
- hm.put(2,"abc");
- hm.put(3,"def");
- hm.put(4,"ghi");
- hm.put(5,"jkl");
- hm.put(6,"mno");
- hm.put(7,"pqrs");
- hm.put(8,"tuv");
- hm.put(9,"wxyz");
- for(int i=1;i<10;i++)
- sop(hm.get(i));
- }
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- }
复制代码 |