且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java泛型参数与泛型参数的基础

更新时间:2022-10-15 15:49:54

您可以使您的函数具有通用性:

  private static< E extends Object> String newName(E object,
HashMap< E,Integer> nameIndexMap){
....
}

这将函数的两个参数绑定在一起,因此对于 HashMap< String,Integer> ,您只能传递 String 实例作为第一个参数。这可能是也可能不是你想要的:如果你只想从地图获取元素,Jon的解决方案更简单,但是如果你想将这个对象添加到地图中,这是唯一的选择。


I am wondering if there's an elegant solution for doing this in Java (besides the obvious one - of declaring a different/explicit function. Here is the code:

private static HashMap<String, Integer> nameStringIndexMap 
        = new HashMap<String, Integer>();
private static HashMap<Buffer, Integer> nameBufferIndexMap 
        = new HashMap<Buffer, Integer>();

// and a function
private static String newName(Object object, 
        HashMap<Object, Integer> nameIndexMap){
    ....
}

The problem is that I cannot pass nameStringIndexMap or nameBufferIndexMap parameters to the function. I don't have an idea about a more elegant solution beside doing another function which explicitly wants a HashMap<String, Integer> or HashMap<Buffer, Integer> parameter.

My question is: Can this be made in a more elegant solution/using generics or something similar?

Thank you,

Iulian

You could make your function generic too:

private static <E extends Object> String newName(E object, 
        HashMap<E, Integer> nameIndexMap){
    ....
}

This bounds the two parameters of the function together, so for a HashMap<String, Integer> you can only pass String instances as first parameter. This may or may not be what you exactly want: if you only want to get elements from the map, Jon's solution is simpler, but if you want to add this object to the map, this one is the only choice.