Java泛型参数与泛型参数的基础 [英] Java generics parameters with base of the generic parameter

查看:125
本文介绍了Java泛型参数与泛型参数的基础的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



<$ p

我想知道是否有一个优雅的解决方案可以在Java中执行此操作(除了显而易见的 - 声明不同的/显式函数外)。 $ b $ private static HashMap< String,Integer> nameStringIndexMap
= new HashMap< String,Integer>();
private static HashMap< Buffer,Integer> nameBufferIndexMap
= new HashMap< Buffer,Integer>();

//和函数
private static String newName(Object object,
HashMap< Object,Integer> nameIndexMap){
....
}

问题是我无法传递 nameStringIndexMap nameBufferIndexMap 参数。我没有关于更明智的解决方案,除了做另一个显式地需要 HashMap< String,Integer> HashMap< Buffer,Integer> 参数。

我的问题是:
在一个更优雅的解决方案/使用泛型或类似的东西?

谢谢,



Iulian

解决方案

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

  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.

这篇关于Java泛型参数与泛型参数的基础的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆