跳至主要内容

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

Implement isdigit

It is seems very easy to implement c library function isdigit , but for a library code, performance is very important. So we will try to implement it and make it faster. Function So, first we make it right. int isdigit ( char c) { return c >= '0' && c <= '9' ; } Improvements One – Macro When it comes to performance for c code, macro can always be tried. #define isdigit (c) c >= '0' && c <= '9' Two – Table Upper version use two comparison and one logical operation, but we can do better with more space: # define isdigit(c) table[c] This works and faster, but somewhat wasteful. We need only one bit to represent true or false, but we use a int. So what to do? There are many similar functions like isalpha(), isupper ... in c header file, so we can combine them into one int and get result by table[c]&SOME_BIT , which is what source do. Source code of ctype.h : # define _ISbit(bit) (1 << (