0

Am Using super for Runnable interface and define Object type to store there am not get any compile error, but for the below code MyRunnale(i) am using MyObject to store but compiler raise a compile error: Type mismatch
Please explain me why am getting compile error & why it is getting there.

class Test 
{

    public static void main(String[] args) {
        ArrayList<? super Runnable> a1 = new ArrayList<Object>();
        // Here am not getting any CTE but for the below code
        ArrayList<? super MyRunnable> a2 = new ArrayList<MyObject>();
        // compile error: Type mismatch: cannot convert from ArrayList<MyObject> to
        // ArrayList<? super MyRunnable>
    }
}

class MyObject {
}
interface MyRunnable {
}
class MyThread extends MyObject implements MyRunnable {
}
user207421
  • 305,947
  • 44
  • 307
  • 483

1 Answers1

0

When you use ArrayList<? super Runnable>, it means the ArrayList can refer to a ArryList of Runnable and any super type of Runnable (In this case ArrayList<Runnable>() or ArrayList<Object>()).

But MyObject is a sub type of Runnable. Hence it doesn't allow you to assign an ArrayList<MyObject>() to it.

If you want to refer ArrayList<MyObject>(), you should use ArrayList<? extends Runnable>.

But make sure you satisfy the PECS rule.

Community
  • 1
  • 1
Codebender
  • 14,221
  • 7
  • 48
  • 85
  • *it means the ArrayList will accept Runnable and any super type of Runnable*. The wording here is a bit ambiguous because the `add` method can actually accept any class that implements `Runnable`. (The statement that `ArrayList` can accept any class that **is-a** `Runnable` would be a bit more correct) – Chetan Kinger Jul 18 '15 at 09:09
  • How can I make MyObject to accept to store in MyRunnable ? and can you suggest me any code reference . – user3345206 Jul 18 '15 at 09:24