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());
}