Java Interview Question

Use this advanced question and answer to prepare for your next Java interview.

Is the code compile-time and run-time safe? What do I and K stand for? What is the use of the extends keyword in both places? Explain the get method definition. Explain the wildcard symbols.

class A<K, I extends List<K>> {
  public K get(final int index, final I list) {
    return list.get(idx);

class B extends A<String, LinkedList<String>> { }

Class C {
  public static void main(String...args) {
    A<Integer, ArrayList<Integer>> a = new A<>;
    B b = new B();
    A<?, ?> g;
    A<? extends Integer, ?> f;
    g = a;
    g = b;
    f = a;

Yes, this code is compile-time and run-time safe.

I and K are Generic type parameters used to ensure type safety.

The extends keyword in the first line defines the scope of the I parameter. The I parameter can only be a sub-type of List of type K. K by default extends Object.

The second extends keyword is used for inheriting class A and fixing the type parameters of A to String and LinkedList.

The get method takes an index integer and a List of type K as the parameters. It returns the list value at index, which will have a return type K because the list parameter is fixed to K.

For example, when get is called on instance b of class B, get will take a LinkedList<String> and return the String at index.

The wildcard symbols indicate that g can have any type within the bounds of the parameters. That is why a and b can be assigned to it. In the case of f, the first parameter gets limited to Integer sub-types, so only a can be assigned to it, not b. f can be assigned to g, but not the other way round.

Looking for developers?