有没有Python的defaultdict的Java等价物? [英] is there a Java equivalent of Python's defaultdict?
问题描述
在Python中, defaultdict
类提供了一种方便的方法来创建从 key - > [值列表]
,在以下示例中,
来自集合import defaultdict
d = defaultdict(list)
d [1] .append(2)
d [1] .append(3)
#d现在是{1:[2,3]}
在Java中是否有与此相当的功能?
没有任何东西给出默认代码的行为。不过,在Java中创建自己的默认字典并不会那么困难。
import java.util.HashMap;
import java.util.List;
public class DefaultDict< K,V>扩展HashMap< K,V> {
Class< V>克拉斯;
public DefaultDict(Class klass){
this.klass = klass;
}
@Override
public V get(Object key){
V returnValue = super.get(key);
if(returnValue == null){
try {
returnValue = klass.newInstance();
} catch(Exception e){
throw new RuntimeException(e);
}
this.put((K)key,returnValue);
}
return returnValue;
$ b
这个类可以像下面一样使用:
public static void main(String [] args){
DefaultDict< Integer,List< Integer>> dict =
new DefaultDict< Integer,List< Integer>>(ArrayList.class);
dict.get(1).add(2);
dict.get(1).add(3);
System.out.println(dict);
}
该代码将打印: {1 = [2 ,3]}
In Python, the defaultdict
class provides a convenient way to create a mapping from key -> [list of values]
, in the following example,
from collections import defaultdict
d = defaultdict(list)
d[1].append(2)
d[1].append(3)
# d is now {1: [2, 3]}
Is there an equivalent to this in Java?
There is nothing that gives the behaviour of default dict out of the box. However creating your own default dict in Java would not be that difficult.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class DefaultDict<K, V> extends HashMap<K, V> {
Class<V> klass;
public DefaultDict(Class klass) {
this.klass = klass;
}
@Override
public V get(Object key) {
V returnValue = super.get(key);
if (returnValue == null) {
try {
returnValue = klass.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
this.put((K) key, returnValue);
}
return returnValue;
}
}
This class could be used like below:
public static void main(String[] args) {
DefaultDict<Integer, List<Integer>> dict =
new DefaultDict<Integer, List<Integer>>(ArrayList.class);
dict.get(1).add(2);
dict.get(1).add(3);
System.out.println(dict);
}
This code would print: {1=[2, 3]}
这篇关于有没有Python的defaultdict的Java等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!