将值添加到ArrayList的映射

huangapple go评论81阅读模式
英文:

Map values being added to ArrayList

问题

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?**
英文:

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

class Solution {
public List&lt;List&lt;String&gt;&gt; groupAnagrams(String[] strs) {
    if (strs.length == 0) return new ArrayList();
    Map&lt;String, List&gt; ans = new HashMap&lt;String, List&gt;();
    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?

答案1

得分: 3

return new ArrayList(ans.values())

将其分解并查看每个指令

1. new ArrayList - 创建一个包含一些值的新对象

2. ans.values() - 从一个collectionMap<K,V>)中获取值,该方法返回所有的V

注意,VList,而all V应该是所有Lists的连接(假设引用)。

英文:

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

答案2

得分: 0

ans.values() 返回 Collection<List<String>>,你需要返回 List<List<String>>。ArrayList 类有一个以 Collection 为参数的构造函数,详见文档

英文:

ans.values() returns Collection&lt;List&lt;String&gt;&gt; and you need to return List&lt;List&lt;String&gt;&gt;. ArrayList class has constructor with Collection as a parameter, see the docs.

答案3

得分: 0

根据java文档,ArrayList类具有可以从指定的集合构造元素列表的构造函数。HashMap也是接口集合的实现。

英文:

According to java doc ArrayList class has the constructor which can construct the list of elements from the specified collection. HasMap is also implementation of interface collection.

huangapple
  • 本文由 发表于 2020年4月7日 14:31:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/61074054.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定