[英]How Can I create method which use Java generics put the maps key to list?
public <T> List<T> map2list(Map<T, T> map){
List<T> list = new ArrayList<T>(map.keySet());
return list;
}
My Method like this... But it does not work. 我的方法是这样的...但是它不起作用。
Maybe your map is empty, because the example below works: 也许您的地图是空的,因为下面的示例有效:
public class Utils {
public <T, K> List<T> map2list(Map<T, K> map) {
List<T> list = new ArrayList<T>(map.keySet());
return list;
}
/**
* @param args
*/
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("test1", 1);
map.put("test2", 2);
map.put("test3", 3);
Utils t = new Utils();
List<String> result = t.map2list(map);
for (String key : result) {
System.out.println(key);
}
}
}
printing the following: 打印以下内容:
test2
测试2
test3测试3
test1测试1
If your map in argument is of String
as key & Integer
as value, try following method, 如果您在参数中的映射是将
String
作为键,将Integer
作为值,请尝试以下方法,
public static <T, L> List<T> map2list (Map<T, L> map) {
List<T> list = new ArrayList<T>(map.keySet());
return list;
}
<T>
define only one type for the runtime type-aguments of your map. <T>
仅为映射的运行时类型参数定义一种类型。 So if you have different types of arguments for the generics of your map, you can change it like this by defining two generic type T and for example K: 因此,如果您对地图的泛型使用不同类型的参数,则可以通过定义两个泛型T和例如K来更改它:
public static <T,K> List<T> map2list(Map<T, K> map){
List<T> list = new ArrayList<T>(map.keySet());
return list;
}
And it will work. 它将起作用。
Also this situation supports that if you want to pass Map<String,String>
or generally Map<T,T>
too. 同样,这种情况也支持如果要传递
Map<String,String>
或通常也传递Map<T,T>
。
Hope this would help. 希望这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.