按类型键入集合

时间:2012-06-26 13:37:57

标签: java android

我希望有一个实现某个界面的对象集合,但我想在集合中只有一个具体类型。

collection of implementers of dog:
 - instance of dachshund
 - instance of beagle
 - instance of corgi

在.NET中,有一个“KeyedByTypeCollection”。 Java中是否存在类似的东西,我可以在Android上使用它?

谢谢!

4 个答案:

答案 0 :(得分:2)

如果您愿意使用第三方图书馆 - 如果您不关心维护订单 - Guava's ClassToInstanceMap似乎适用于此处。

ClassToInstanceMap<Dog> map = MutableClassToInstanceMap.create();
map.putInstance(Corgi.class, new Corgi("Spot"));
map.putInstance(Beagle.class, new Beagle("Lady"));
Corgi corgi = map.getInstance(Corgi.class); // no cast required

(披露:我向Guava捐款。)

答案 1 :(得分:1)

你应该看看泛型。例如。: List<Dogs> dogList = new ArrayList<Dogs>();

编辑:在您的收藏集中只有唯一的实例,您应该使用Set<Dogs> dogList = new HashSet<Dogs>();

答案 2 :(得分:0)

我认为您需要一个自定义的HaspMap,它将使用相同的键维护多个值,

因此,创建一个扩展HashMap并将值放入其中的简单类。

public class MyHashMap extends LinkedHashMap<String, List<String>> {

    public void put(String key, String value) {
        List<String> current = get(key);
        if (current == null) {
            current = new ArrayList<String>();
            super.put(key, current);
        }
        current.add(value);
    }
}

现在,创建MyHashMap的实例并将值放入其中,如下所示

        MyHashMap hashMap = new MyHashMap();
        hashMap.put("dog", "dachshund");
        hashMap.put("dog", "beagle");
        hashMap.put("dog", "corgi");
        Log.d("output", String.valueOf(hashMap));

<强>输出

{dog=[dachshund, beagle, corgi]}

答案 3 :(得分:0)

这可能是您正在寻找的: 请参阅代码中的注释

// two Dog(interface) implementations
        // Beagle, Dachshund implements Interface Dog.
        final Dog d1 = new Beagle();
        final Dog d2 = new Dachshund();

        // here is your collection with type <Dog>
        final Set<Dog> set = new HashSet<Dog>();
        set.add(d1);
        set.add(d2);

        // see output here
        for (final Dog d : set) {
            System.out.println(d.getClass());
        }

        // you can fill them into a map
        final Map<Class, Dog> dogMap = new HashMap<Class, Dog>();
        for (final Dog d : set) {
            // dog instances with same class would be overwritten, so that only one instance per type(class)
            dogMap.put(d.getClass(), d); 
        }

system.out.println行的输出类似于:

class test.Beagle
class test.Dachshund