简体   繁体   中英

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. 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.

In theory something like this (I know this is not working Java code):

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.

You should also consider making the type of the value List<T> instead of ArrayList<T> - see Liskov substitution principle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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