Map values being added to ArrayList

afraah :

I'm having trouble understanding how the last line of code is valid.

class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
    if (strs.length == 0) return new ArrayList();
    Map<String, List> ans = new HashMap<String, List>();
    for (String s : strs) {
        char[] ca = s.toCharArray();
        Arrays.sort(ca);
        String key = String.valueOf(ca);
        if (!ans.containsKey(key)) ans.put(key, new ArrayList());
        ans.get(key).add(s);
    }
    return new ArrayList(ans.values());
}

}

The line of code: " return new ArrayList(ans.values());" Are the values being inserted one by one- what exactly is happening?

Traian GEICU :

return new ArrayList(ans.values())
Break it down and see each instructions
1. new ArrayList - new object populated with some values
2 ans.values() - values coming from a collection: Map<K,V> and the method is returning all V.
Note V is List and all V should be a concatenation of all Lists (assume references)

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=477875&siteId=1