简体   繁体   English

以通用类型作为键/值的 Java 通用映射

[英]Java Generic Map with Generic Type as key/ values

I want to write a method which takes a Map as an parameter, which can contain any object as its value.我想编写一个以 Map 作为参数的方法,该方法可以包含任何对象作为其值。 I am trying to implement it using generics, but I am unable to implement it.我正在尝试使用泛型来实现它,但我无法实现它。

Below is the code that I have tried so far.以下是我迄今为止尝试过的代码。 This code as two methods: genericTest , where I am trying to implement a generic solution, and nonGenericTest , which is what I actually want to do with the generic solution but is implemented without using generics.这段代码作为两种方法: genericTest ,我试图实现一个通用解决方案,以及nonGenericTest ,这是我真正想要用通用解决方案做的,但不使用泛型实现。 Basically, the second method is the one which I want to convert to generics.基本上,第二种方法是我想转换为泛型的方法。

What am I doing wrong?我究竟做错了什么?

import java.util.Iterator;
import java.util.Map;

public class Test {
    //V cannot be resolve to a type
    public void genericTest(Map<String, V> params) {
    }

    public void nonGenericTest(Map<String, Object> params) {

        Iterator<String> it = params.keySet().iterator();
        while (it.hasNext()) {
            String key =  it.next();
            Object value = params.get(key);
            if(value instanceof String){
                String val1=(String) value;
                // do something 
            }else if(value instanceof Integer){
                Integer val1 = (Integer) value;
            } 
        }
    }
}

I am getting compiler error as shown in the code.如代码所示,我收到编译器错误。

You've got two options:你有两个选择:

  • Introduce V as a type parameter to the class.V作为类型参数引入类。

     public class Test<V>
  • Introduce V as a type parameter to that function.V作为该函数的类型参数引入。

     public <V> void genericTest(Map<String, V> params)

I would suggest to use it with the class definition like this:我建议将它与这样的类定义一起使用:

public class SettingsClient<T> extends TestWebserviceClient {

    private Map<String, List<T>> mapWithAllPojoLists = new HashMap<>();

}

Inside the method, you can read/ write to the map like this:在方法内部,您可以像这样读取/写入地图:

   public List<Discount> getListOfDiscounts() {

        if (mapWithAllPojoLists.get("discount") != null) {
            return (List<Discount>) mapWithAllPojoLists.get("discount");
        }

        GetDiscountsResponse response = getGetDiscountsResponse();
        ArrayOfDiscount arrayOfDiscount = response.getGetDiscountsResult().getValue();

        List<Discount> discounts = arrayOfDiscount.getDiscount();

        if (discounts == null) {
            return new ArrayList<>();
        }

        mapWithAllPojoLists.put("discount", (List<T>) discounts);
        return discounts;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM