在Java中将Map键值从一个类复制到另一个类

时间:2016-03-09 15:31:10

标签: java class hashmap set maps

请允许任何人帮我在Java中将Map键值从一个类复制到另一个类。

示例:

            public class FirstClass
            {   
               public static Map<String, Integer> firstMethod()
               {
                  Map<String, Integer> firstMap = new HashMap <String, Integer>();
                  firstMap.put("1234", 1000000);
                  firstMap.put("2345", 2000000);
                  firstMap.put("3456", 3000000);
                  firstMap.put("4567", 4000000);
                  return firstMap;
               }   
            }

   public class SecondClass

           public SecondClass()
           {
             instanceSet = new HashSet<ThirdClass>();
           }

      public void addInstance(String string)
       {
         ThirdClass integer = new ThirdClass(string);
         instanceSet.add(integer);     
       }   

       public void someMethod(Map<String, Integer> secondMap)
               {
                  for (ThirdClass instance : instanceSet)
                  {
                     if(secondMap.containsKey(instance.getinstanceNumber()))
                     {
                       //what should go in here??
                     }  
                  }   
               }  

基本上,如果instanceSet包含在firstMap中找到的键,那么如何提取该键的Integer值并将其复制到secondMap中相同键的Integer值?

我在网上浏览过,但我发现的所有代码示例似乎都不起作用,因为地图存储在不同的类中。

1 个答案:

答案 0 :(得分:0)

像这样的代码。您需要firstMapsomeMethod的引用,反之亦然,具体取决于您要复制到的位置。

if(secondMap.containsKey(instance.getinstanceNumber())) {
       firstMap.put(instance.getinstanceNumber(), secondMap.get(instance.getinstanceNumber()));
} 

像这样 -

public class FirstClass {
    public Map<String, Integer> firstMap;

    public FirstClass() {
        firstMap = new HashMap <String, Integer>();
        firstMap.put("1234", 1000000);
        firstMap.put("2345", 2000000);
        firstMap.put("3456", 3000000);
        firstMap.put("4567", 4000000);
    }

    public void updateMap(String key, Integer value) {
        firstMap.put(key, value);
    }
}

public class SecondClass {

    private Set<ThirdClass> instanceSet;
    private FirstClass firstClass;

    public SecondClass() {
        instanceSet = new HashSet<ThirdClass>();
        firstClass = new FirstClass();
    }

    public void addInstance(String string) {
        ThirdClass integer = new ThirdClass(string);
        instanceSet.add(integer);
    }

    public void someMethod(Map<String, Integer> secondMap) {
        for (ThirdClass instance : instanceSet) {
            if (secondMap.containsKey(instance.getinstanceNumber())) {
                firstClass.updateMap(instance.getinstanceNumber(), secondMap.get(instance.getinstanceNumber()));
            }
        }
    }
}