Compile Error on Java 7 Diamond Operator: ArrayList<>();

Simulant picture Simulant · Sep 27, 2012 · Viewed 26.4k times · Source

I have this line of code:

List<IObserver<?>> observers = new ArrayList<>();

and get the 3 following Errors:

Cannot instantiate the type ArrayList<?>
Syntax error on token "<", ? expected after this token
Type mismatch: cannot convert from ArrayList<?> to List<IObserver<?>>

I am using Eclipse 3.7, I installed JDK 7 update 5 and the Project is set to use the JRE System Library[JavaSE1.7] in the Build Path.

Passing in the IObserver<?> on the right side compiles fine, but I have to use the diamond operator.

I think this is a configuration problem, but I can't figure out what I have missed.

Answer

obe6 picture obe6 · Sep 27, 2012

The code should work : diamond operator is used correctly. I suggest you to install a more recent version of Eclipse (Indigo or Juno), and set the compiler compliance level to 1.7.

Here is a simple working example (IObserver is invented here). Print to the console : "we are 2"

package it.ant.test;

import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        List<IObserver<?>> observers = new ArrayList<>();
        IObserver<String> stringObserver = new Observer<>();
        IObserver<Integer> integerObserver = new Observer<>();
        stringObserver.addObserved("we are ");
        integerObserver.addObserved(2);

        observers.add(stringObserver);
        observers.add(integerObserver);

        for (IObserver<?> o : observers) {
            System.out.print(o.getObserved());
        }

    }
}

interface IObserver<T> {    
    void addObserved(T t);
    T getObserved();
}

class Observer<T> implements IObserver<T> { 
    private T observed;

    @Override
    public void addObserved(T observed) {
        this.observed = observed;

    }

    @Override
    public T getObserved() {
        return observed;
    }
}