Frage

The following code snippet has been taken from Commons framework's CollectionUtils.java file:

private static class CardinalityHelper<O> {
    final Map<O, Integer> cardinalityA, cardinalityB;

    public CardinalityHelper(final Iterable<? extends O> a,
            final Iterable<? extends O> b) {
        cardinalityA = CollectionUtils.<O> getCardinalityMap(a);
        cardinalityB = CollectionUtils.<O> getCardinalityMap(b);
    }

    public final int max(final Object obj) {
        return Math.max(freqA(obj), freqB(obj));
    }

    public final int min(final Object obj) {
        return Math.min(freqA(obj), freqB(obj));
    }

    public int freqA(final Object obj) {
        return getFreq(obj, cardinalityA);
    }

    public int freqB(final Object obj) {
        return getFreq(obj, cardinalityB);
    }

    private final int getFreq(final Object obj,
            final Map<?, Integer> freqMap) {
        final Integer count = freqMap.get(obj);
        if (count != null) {
            return count.intValue();
        }
        return 0;
    }
}

getCardinalityMap returns <O> Map<O, Integer> Can somebody please help me to understand

  1. what does cardinalityA = CollectionUtils.<O> getCardinalityMap(a); means? Is this some kind of typecasting?
  2. What does return type <O> Map<O, Integer> means?
  3. What is this trick called?

Thanks

War es hilfreich?

Lösung

1) what does cardinalityA = CollectionUtils. getCardinalityMap(a); means? Is this some kind of typecasting?

It is not a typecasting. It is explicit setting generic parameter for generic method. CardinalityHelper has generic parameter <O> as you can see from the declaration:

private static class CardinalityHelper<O> {

It is typesafe way for the clients of the CardinalityHelper to use this class.

2) What does return type <O> Map<O, Integer> means?

- generic parameter declaration. Map - return type.

3) What is this trick called?

It is using Java Generic methods.

You also can find simular usage in standart JDK library. For example: java.util.Collections.sort(java.util.List)

Java implementation of Metaprogramming principles is very limited, so you are able to use only Generic Type parameters to create typesafe containers, which required by strongly typed nature of Java.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top