I have a question regarding the initiation of ArrayList in Java.
As far as I know I have to specify the type of my ArrayList when initialize it. For example:
ArrayList<String> names = new ArrayList<String>();
or
ArrayList<String> names = new ArrayList<>();
However, when I want to write a code to return an ArrayList of List,
which is from the values of a map
Map<String, List> map = new HashMap<>();
If I tried to use the following, error happens
return new ArrayList<>(map.values())
or
return new ArrayList<List<String>>(map.values())
Instead, I can only use the one, without the <>.
return new ArrayList(map.values())
Could anyone let me know when I should or should not use the <> when I initialize an ArrayList(or any other objects)?
The original code is as written below
public List<List<String>> groupAnagrams(String[] strs) {
if (strs.length == 0) return new ArrayList<>();
Map<String, List> res = new HashMap<>();
for (String s : strs) {
char[] charArray = s.toCharArray();
Arrays.sort(charArray);
String key = String.valueOf(charArray);
if (!res.containsKey(key)) res.put(key, new ArrayList());
res.get(key).add(s);
}
return new ArrayList<List<String>>(res.values());
}
CodePudding user response:
public List<List<String>> groupAnagrams(String[] strs) {
...
Map<String, List> res = new HashMap<>();
...
res.put(key, new ArrayList());
...
return new ArrayList<List<String>>(res.values());
}
The problem here is that res.values()
isn't a Collection<List<String>>
, which is what would be required: it's a Collection<List>
.
The elements of res.values()
are raw types: you've used List
without specifying the type parameters.
Raw types disable type checking, meaning you can end up putting things into collections with types you don't want.
Every time you use a generic type, make sure it has type parameters (or diamonds, if allowed:
public List<List<String>> groupAnagrams(String[] strs) {
...
Map<String, List<String>> res = new HashMap<>();
...
res.put(key, new ArrayList<>());
...
return new ArrayList<>(res.values());
}
CodePudding user response:
Because the type of map value is List , but you define the type of list value is string.
And suggest use guava Multimap instead of Map<String ,List>