Michael Anderson
Michael Anderson

Reputation: 73480

Can we distinguish the results of diamond operator from raw constructor?

I have some code that I would write

GenericClass<Foo> foos = new GenericClass<>();

While a colleague would write it

GenericClass<Foo> foos = new GenericClass();

arguing that in this case the diamond operator adds nothing.

I'm aware that constructors that actually use arguments related to the generic type can cause a compile time error with <> instead of a run time error in the raw case. And that the compile time error is much better. (As outlined in this question)

I'm also quite aware that the compiler (and IDE) can generate warnings for the assignment of raw types to generics.

The question is instead for the case where there are no arguments, or no arguments related to the generic type. In that case, is there any way the constructed object GenericClass<Foo> foos can differ depending on which constructor was used, or does Javas type erasure guarantee they are identical?

Upvotes: 26

Views: 10012

Answers (5)

Michael Anderson
Michael Anderson

Reputation: 73480

This is not a complete answer - but does provide a few more details.

While you can not distinguish calls like

GenericClass<T> x1 = new GenericClass<>();
GenericClass<T> x2 = new GenericClass<T>();
GenericClass<T> x3 = new GenericClass();

There are tools that will allow you to distinguish between

GenericClass<T> x4 = new GenericClass<T>() { };
GenericClass<T> x5 = new GenericClass() { };

Note: While it looks like we're missing new GenericClass<>() { }, it is not currently valid Java.

The key being that type information about the generic parameters are stored for anonymous classes. In particular we can get to the generic parameters via

Type superclass = x.getClass().getGenericSuperclass();
Type tType = (superclass instanceof ParameterizedType) ?
             ((ParameterizedType) superclass).getActualTypeArguments()[0] : 
             null;
  • For x1, x2, and x3 tType will be an instance of TypeVariableImpl (the same instance in all three cases, which is not surprising as getClass() returns the same object for all three cases.

  • For x4 tType will be T.class

  • For x5 getGenericSuperclass() does not return an instance of ParameterizedType, but instead a Class (infact GenericClass.class)

We could then use this to determine whether our obect was constructed via (x1,x2 or x3) or x4 or x5.

Upvotes: 0

Dragan Bozanovic
Dragan Bozanovic

Reputation: 23552

In your specific example: Yes, they are identical.

Generally: Beware, they may not be!

The reason is that different overloaded constructor/method may be invoked when raw type is used; it is not only that you get better type safety and avoid runtime ClassCastException.

Overloaded constructors

public class Main {

    public static void main(String[] args) {
        Integer anInteger = Integer.valueOf(1);
        GenericClass<Integer> foosRaw = new GenericClass(anInteger);
        GenericClass<Integer> foosDiamond = new GenericClass<>(anInteger);
    }

    private static class GenericClass<T> {

        public GenericClass(Number number) {
            System.out.println("Number");
        }

        public GenericClass(T t) {
            System.out.println("Parameter");
        }
    }
}

Version with diamond invokes the different constructor; the output of the above program is:

Number
Parameter

Overloaded methods

public class Main {

    public static void main(String[] args) {
        method(new GenericClass());
        method(new GenericClass<>());
    }

    private static void method(GenericClass<Integer> genericClass) {
        System.out.println("First method");
    }

    private static void method(Object object) {
        System.out.println("Second method");
    }

    private static class GenericClass<T> { }
}

Version with diamond invokes the different method; the output:

First method
Second method

Upvotes: 1

Makoto
Makoto

Reputation: 106430

For instantiations of two ArrayLists, one with the diamond operator at the end and one without...

List<Integer> fooList = new ArrayList<>();
List<Integer> barList = new ArrayList();

...the bytecode generated is identical.

LOCALVARIABLE fooList Ljava/util/List; L1 L4 1
// signature Ljava/util/List<Ljava/lang/Integer;>;
// declaration: java.util.List<java.lang.Integer>
LOCALVARIABLE barList Ljava/util/List; L2 L4 2
// signature Ljava/util/List<Ljava/lang/Integer;>;
// declaration: java.util.List<java.lang.Integer>

So there wouldn't any difference between the two as per the bytecode.

However, the compiler will generate an unchecked warning if you use the second approach. Hence, there's really no value in the second approach; all you're doing is generating a false positive unchecked warning with the compiler that adds to the noise of the project.


I've managed to demonstrate a scenario in which doing this is actively harmful. The formal name for this is heap pollution. This is not something that you want to occur in your code base, and any time you see this sort of invocation, it should be removed.

Consider this class which extends some functionality of ArrayList.

class Echo<T extends Number> extends ArrayList<T> {
    public Echo() {

    }

    public Echo(Class<T> clazz)  {
        try {
            this.add(clazz.newInstance());
        } catch (InstantiationException | IllegalAccessException e) {
            System.out.println("YOU WON'T SEE ME THROWN");
            System.exit(-127);
        }
    }
}

Seems innocuous enough; you can add an instance of whatever your type bound is.

However, if we're playing around with raw types...there can be some unfortunate side effects to doing so.

final Echo<? super Number> oops = new Echo(ArrayList.class);
oops.add(2);
oops.add(3);

System.out.println(oops);

This prints [[], 2, 3] instead of throwing any kind of exception. If we wanted to do an operation on all Integers in this list, we'd run into a ClassCastException, thanks to that delightful ArrayList.class invocation.

Of course, all of that could be avoided if the diamond operator were added, which would guarantee that we wouldn't have such a scenario on our hands.

Now, because we've introduced a raw type into the mix, Java can't perform type checking per JLS 4.12.2:

For example, the code:

List l = new ArrayList<Number>();
List<String> ls = l;  // Unchecked warning

gives rise to a compile-time unchecked warning, because it is not possible to ascertain, either at compile time (within the limits of the compile-time type checking rules) or at run time, whether the variable l does indeed refer to a List<String>.

The situation above is very similar; if we take a look at the first example we used, all we're doing is not adding an extra variable into the matter. The heap pollution occurs all the same.

List rawFooList = new ArrayList();
List<Integer> fooList = rawFooList;

So, while the byte code is identical (likely due to erasure), the fact remains that different or aberrant behavior can arise from a declaration like this.

Don't use raw types, mmkay?

Upvotes: 11

Erick G. Hagstrom
Erick G. Hagstrom

Reputation: 4945

The JLS is actually pretty clear on this point. http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.1.2

First it says "A generic class declaration defines a set of parameterized types (§4.5), one for each possible parameterization of the type parameter section by type arguments. All of these parameterized types share the same class at run time."

Then it gives us the code block

Vector<String>  x = new Vector<String>();
Vector<Integer> y = new Vector<Integer>();
boolean b = x.getClass() == y.getClass();

and says that it "will result in the variable b holding the value true."

The test for instance equality (==) says that both x and y share exactly the same Class object.

Now do it with the diamond operator and without.

Vector<Integer> z = new Vector<>();
Vector<Integer> w = new Vector();
boolean c = z.getClass() == w.getClass();
boolean d = y.getClass() == z.getClass();

Again, c is true, and so is d.

So if, as I understand, you're asking whether there is some difference at runtime or in the bytecode between using the diamond and not, the answer is simple. There is no difference.

Whether it's better to use the diamond operator in this case is a matter of style and opinion.

P.S. Don't shoot the messenger. I would always use the diamond operator in this case. But that's just because I like what the compiler does for me in general w/r/t generics, and I don't want to fall into any bad habits.

P.P.S. Don't forget that this may be a temporary phenomenon. http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.8 warns us that "The use of raw types in code written after the introduction of generics into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types."

Upvotes: 3

Tagir Valeev
Tagir Valeev

Reputation: 100209

You may have problem with default constructor if your generic arguments are limited. For example, here's sloppy and incomplete implementation of the list of numbers which tracks the total sum:

public class NumberList<T extends Number> extends AbstractList<T> {
    List<T> list = new ArrayList<>();
    double sum = 0;

    @Override
    public void add(int index, T element) {
        list.add(index, element);
        sum += element.doubleValue();
    }

    @Override
    public T remove(int index) {
        T removed = list.remove(index);
        sum -= removed.doubleValue();
        return removed;
    }

    @Override
    public T get(int index) {
        return list.get(index);
    }

    @Override
    public int size() {
        return list.size();
    }

    public double getSum() {
        return sum;
    }
}

Omitting the generic arguments for default constructor may lead to ClassCastException in runtime:

List<String> list = new NumberList(); // compiles with warning and runs normally
list.add("test"); // throws CCE

However adding the diamond operator will produce a compile-time error:

List<String> list = new NumberList<>(); // error: incompatible types
list.add("test");

Upvotes: 1

Related Questions