英文:
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<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?
答案1
得分: 3
return new ArrayList(ans.values())
将其分解并查看每个指令
1. new ArrayList - 创建一个包含一些值的新对象
2. ans.values() - 从一个collection(Map<K,V>)中获取值,该方法返回所有的V。
注意,V是List,而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<K,V> 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<List<String>> and you need to return List<List<String>>. 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论