跳至主要内容

Generic Common Usage

I was asked some confusing point about generic during my interview, so I review the generic after it. Following is some note.

Basic use

First, we write our simple container:

public class Container<T> {
    private T[] a;

    private T get(int i) {
        return a[i];
    }

    private void set(int i, T t) {
        a[i] = t;
    }
}

In our example, generic only work like some place holder which can be replaced by Integer or String or Object.

bounded type parameter

Now, we move to more complex usage.
We add one more method to our container: addAll to add all element from other Collection.

public void simpleAddAll(Collection<T> c) {
    for (T t : c) {
        list.add(t);
    }
}   

This works, but somewhat limited. We can only add the same type element into our container rather than like what standard library can do. Learning from the jdk source, we can change our method into:

public <E extends T> void addAll(Collection<E> c) {
    for (E t : c) {
        list.add(t);
    }
}

Now, we can not only add same type, but also the sub-type. There E extend T give a upper bound for E to limit the range of E as the sub-type of T, so we can add element of E into our container safely.


We now want our element in the container to be comparable because we want our container to be in some kind of order.

public class Container<T extends Comparable> {
}

This works, but Comparable itself is also has generic type parameter means which type our container can compared with. So we move to the following:

public class Container<T extends Comparable<T>> {
}

This means T is comparable with itself.

no <E super T>

When we want to copy our element out, we may implement it in the way like addAll:

public <E extends T> void copyOut(Collection<E> c) {
    for (T t : list) {
        c.add(t);
    }
}

But this syntax is not permitted by Java compiler, so we will use wildcard to make it.

wildcard

bounded wildcard

public void copyOut(Collection<? super T> c) {
    for (T t : list) {
        c.add(t);
    }
}

<? super T> set a lower bound, which means our collection’s type can be a super type of T. Parameter is Collection<Father>, so we can add a Son into it.
Back to our addAll, we can also use wildcard to implement it.

public void addAllAgain(Collection<? extends T> collection) {
    for (T t : collection) {
        list.add(t);
    }
}

We continue to develop our container with more method. We are going to add a util method used to copy from one collection to another.

public static <E> void copyTo(Collection<? extends E> p, Collection<? super E> c) {
    for (E e : p) {
        c.add(e);
    }
}

We can see the principle of this code from the inheritance tree:

    A -- <? super B>
    |
    |
    B -- <? extends B> <? super B>
    |
    |
    C -- <? extends B>


/**
 We take an element from Collection<? extends B>, so it at least to be a B; Now we have a Collection<? super B>, so it must be able to hold a B.
*/

Now, we are going to use our container like the following:

public class Base implements Comparable<Base> {
    // ...
}

public class Sub extends Base {
}

Container<Base> c = new Container<>(); // fine
Container<Sub> s = new Container<>(); // compiler error

You may confused about the compiler error, but let’s see what the error message say:

type argument Sub is not within bounds of type-variable T
        Container<Sub> s = new Container<Sub>();
                  ^
  where T is a type-variable:
    T extends Comparable<T> declared in class Container

That means Sub extends Comparable<Sub> is not met, but Sub can be compared as Base, i.e. Sub extends Comparable<Base>. So we can make it T as:

// means T can be compared with its super type
public class Container<T extends Comparable<? super T>>

no bound wildcard

We can also use wildcard without bound:

public static int frequency(Collection<?> c, Object o);
public static <T> int frequency(Collection<T> c, Object o);

They are equal in this example because we only need reading. Let’s see when they are different:

public static void swap(List<?> l, int i, int j) {
    Object t = l.get(i);
    l.set(i, l.get(j)); // compiler error
    l.set(j, t); // compiler error
}

public static <T> void swap(List<T> l, int i, int j) {
    T t = l.get(i);
    l.set(i, l.get(j)); 
    l.set(j, t); 
}

When using wildcard, we can’t write item in because you don’t know what the wildcard is, but using type parameter can.

An interesting code snippet we can see from java source code to overcome this problem when using wildcard:

@SuppressWarnings({"rawtypes", "unchecked"})
public static void swap(List<?> list, int i, int j) {
    // instead of using a raw type here, it's possible to capture
    // the wildcard but it will require a call to a supplementary
    // private method
    final List l = list;
    l.set(i, l.set(j, l.get(i)));
}

Conclusion

  • <? extends T> and <E extends T> have some similarities and differences:
    • <E extends T> define a type parameter; <? extends T> init a type parameter
  • only <? super T>, no <E super T>
  • <? super T> can be used in:
    • compare with father
    • add item into it – Consumer
  • <? extends T> can be used in
    • retrieve item from it

The following is some jdk interfaces, let’s see whether we can understand it:

public static <T> 
void sort(List<T> list, Comparator<? super T> c) {

public static <T>
int binarySearch(List<? extends Comparable<? super T>> list, T key) {

public static <T>
void copy(List<? super T> dest, List<? extends T> src) {

Ref

Written with StackEdit.

评论

此博客中的热门博文

Spring Boot: Customize Environment

Spring Boot: Customize Environment Environment variable is a very commonly used feature in daily programming: used in init script used in startup configuration used by logging etc In Spring Boot, all environment variables are a part of properties in Spring context and managed by Environment abstraction. Because Spring Boot can handle the parse of configuration files, when we want to implement a project which uses yml file as a separate config file, we choose the Spring Boot. The following is the problems we met when we implementing the parse of yml file and it is recorded for future reader. Bind to Class Property values can be injected directly into your beans using the @Value annotation, accessed via Spring’s Environment abstraction or bound to structured objects via @ConfigurationProperties. As the document says, there exists three ways to access properties in *.properties or *.yml : @Value : access single value Environment : can access multi...

Elasticsearch: Join and SubQuery

Elasticsearch: Join and SubQuery Tony was bothered by the recent change of search engine requirement: they want the functionality of SQL-like join in Elasticsearch! “They are crazy! How can they think like that. Didn’t they understand that Elasticsearch is kind-of NoSQL 1 in which every index should be independent and self-contained? In this way, every index can work independently and scale as they like without considering other indexes, so the performance can boost. Following this design principle, Elasticsearch has little related supports.” Tony thought, after listening their requirements. Leader notice tony’s unwillingness and said, “Maybe it is hard to do, but the requirement is reasonable. We need to search person by his friends, didn’t we? What’s more, the harder to implement, the more you can learn from it, right?” Tony thought leader’s word does make sense so he set out to do the related implementations Application-Side Join “The first implementation ...

Learn Spring Expression Language

When reading the source code of some Spring based projects, we can see some code like following: @Value( "${env}" ) private int value ; and like following: @Autowired public void configure (MovieFinder movieFinder, @ Value ("#{ systemProperties[ 'user.region' ] } ") String defaultLocale) { this.movieFinder = movieFinder; this.defaultLocale = defaultLocale; } In this way, we can inject values from different sources very conveniently, and this is the features of Spring EL. What is Spring EL? How to use this handy feature to assist our developments? Today, we are going to learn some basics of Spring EL. Features The full name of Spring EL is Spring Expression Language, which exists in form of Java string and evaluated by Spring. It supports many syntax, from simple property access to complex safe navigation – method invocation when object is not null. And the following is the feature list from Spring EL document : ...