[英]Using generics to add an object of generic type to a map
I have three Maps: 我有三张地图:
Map<Integer,ArrayList<ItemType1>> map1;
Map<Integer,ArrayList<ItemType2>> map2;
Map<Integer,ArrayList<ItemType3>> map3;
I frequently want to look up a key into a map and add an item to it's ArrayList value. 我经常想在地图中查找一个键,并在其ArrayList值中添加一个项目。 I want to make a method that will take as a parameter a map
Map<Integer,ArrayList<T>>
(with an ArrayList value of a generic type T), a key to add to, and an item of type T to add to that map. 我想创建一个方法,将地图
Map<Integer,ArrayList<T>>
(具有通用类型T的ArrayList值),要添加的键以及要添加到的类型T的项作为参数那张地图。
In theory something like this (I know this is not working Java code): 理论上是这样的(我知道这不是Java代码):
private void addToListInMap(Map<Integer,ArrayList<T>> map,Integer keyValue, T itemToAdd){
ArrayList<T> listOfItems= map.get(keyValue);
if(listOfItems == null){
listOfItems= new ArrayList<T>();
map.put(keyValue, listOfItems);
}
listOfItems.add(itemToAdd);
}
How can I achieve something like this using generics? 如何使用泛型实现这样的效果?
This isn't too terribly difficult: provide the generic type as a type argument to your method. 这并不是非常困难:将泛型类型作为方法的类型参数提供。
All your code is missing is the type parameter to it. 您缺少的所有代码都是它的类型参数。 Then, it should "just work".
然后,它应该“正常工作”。
private <T> void addToListInMap(Map<Integer, ArrayList<T>> map,
Integer keyValue, T itemToAdd) {
ArrayList<T> listOfItems = map.get(keyValue);
if (listOfItems == null) {
listOfItems = new ArrayList<T>();
map.put(keyValue, listOfItems);
}
listOfItems.add(itemToAdd);
}
You need to type the method, so code in the method has access to it (to create the new list). 您需要键入方法,因此方法中的代码可以访问它(以创建新列表)。
private static <T> void addToListInMap(Map<Integer,ArrayList<T>> map, Integer keyValue, T itemToAdd {
ArrayList<T> listOfItems = map.get(keyValue);
if (listOfItems == null) {
listOfItems = new ArrayList<T>();
map.put(keyValue, listOfItems);
}
listOfItems.add(itemToAdd);
}
I made the method static
too, since it doesn't need access to any fields to work. 我也将方法设置为
static
,因为它不需要访问任何字段来工作。
You should also consider making the type of the value List<T>
instead of ArrayList<T>
- see Liskov substitution principle 您还应该考虑使用值
List<T>
的类型而不是ArrayList<T>
- 请参阅Liskov替换原则
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.