Machine-translated by Google. Questions are authored in English.
Top

Discussion

The program is run with java -ea Trial105 - what will be the output?

import java.util.*;

public class Trial105
{
    public static void main(String[] args)
    {
        List<String> a = new ArrayList<String>();
        List<Integer> b = new ArrayList<Integer>();
        assert a.getClass() != b.getClass();
        System.out.println(a.getClass() == b.getClass());
    }
}

  • A.An AssertionError is thrown, and the print would have shown true.
  • B.The program prints true
  • C.Compilation fails.
  • D.The program prints false

Answer: A

Generic type arguments are erased at compile time, so both objects are plain ArrayLists at runtime and report the same class. The assertion claiming the classes differ is false and throws. This is why a generic type cannot be recovered from an object with getClass.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.