Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'List<T>' may not contain type objects of type 'Object'

Short:
Is this possible to have a class that isn't a child of the Object?

Long:
I'm working with List<T> which contains implementations of the interface (Operation):

public class OperationQueue<T extends Operation> {

    private final List<T> mQueue = new ArrayList<>();
    ...
}

When I go through this list in the cycle, I mark every finished operation as null, because I have to keep same size and I cannot use iterator (it throws ConcurrentModificationException):

for (int i = 0; i < mQueue.size() && !mState.equals(State.PAUSED); i++) {
    mOperation = mQueue.get(i);
    if (mOperation != null) {
        mOperation.run();
    }
    mQueue.set(i, null);
}

When I pause or finish the queue execution I use:

mQueue.removeAll(Collections.singleton(null));

And Android Studio shows me warning:

'List<T>' may not contain type objects of type 'Object'

How is it possible? I thought that everything is the child of the Object?

Any help would be appreciated.

like image 689
Anton Shkurenko Avatar asked Dec 15 '22 10:12

Anton Shkurenko


2 Answers

Everything is a child of Object: but your List needs them to be a specific type of child of Object, namely: of type T.

Collections.singleton(null) is not a Collection of Ts. Try Collections.<T>singleton(null); by adding the specifier to the method invocation you get back a collection of the specified type.

like image 154
Rich Avatar answered Dec 16 '22 23:12

Rich


In Java all classes derive from the Object class. The only exception is for primitive types, which aren't classes at all. So the short answer is 'no' there's no class which is not an subclass of Object.

The longer answer is that in your mqueue.removeAll(Collections.singleton(null)) call you are coming up against type inference. The compiler is trying to match up the type signature of Collections.singleton(null) with the mqueue.removeAll() parameter and it's failing. The compiler believes that Collections.singleton(null) is returning a Set, because it doesn't know what else to do with 'null' - the only thing you can say about it is that it's an object. And so it's telling you that you can't give removeAll(...) a parameter of Set, because that method is defined as accepting a Collection. Set is a collection, but Object doesn't match T.

To give the compiler enough information you need to give it a type hint - Collections.<T>singleton(null).

like image 41
sisyphus Avatar answered Dec 16 '22 22:12

sisyphus