Page 1 of 1

About Question enthuware.ocajp.i.v8.2.1473 :

Posted: Fri Jul 17, 2015 12:17 pm
by FrodoBaggins
Hi there.

Just to point out that to get this to compile I had to import three different imports.

Re: About Question enthuware.ocajp.i.v8.2.1473 :

Posted: Fri Jul 17, 2015 8:37 pm
by admin
Unless the question is about import statements, you may assume appropriate imports. Many questions in the exam contain just a code fragment. You have to assume that the rest of the code is in place and valid.

Re: About Question enthuware.ocajp.i.v8.2.1473 :

Posted: Tue Jul 21, 2015 10:09 am
by islam.amin099
Hi there,
checkList(new ArrayList(), (ArrayList al) -> al.isEmpty());
If the Predicate requires a List and ArrayList implements List why this doesn't compile?

Re: About Question enthuware.ocajp.i.v8.2.1473 :

Posted: Tue Jul 21, 2015 10:31 am
by admin
You have to think of a lambda expression as a complete class to understand why you cannot use ArrayList instead of a List here.
The lambda expression (ArrayList al) -> al.isEmpty() is actually same as the following class:

Code: Select all

class MyPredicate implements Predicate<List>{ //Here MyPredicate has to implement Predicate<List> because the method checkList has Predicate<List>
   public boolean test(ArrayList al){ //Here the method parameter type is ArrayList because in the lambda expression, you have (ArrayList al).
     return al.isEmpty();
   }
}
You are saying that MyPredicate is a Predicate<List>, which means that its method should be able to accept any kind of List. But in the method test(ArrayList al), you are saying that it will only accept an ArrayList. Do you see that both are contradictory statements? That is why it is not acceptable.

Remember that when you write a lambda expression, you not just passing an object. You are actually declaring a method. Therefore, that method must be compatible with the interface that you are trying to implement with that lambda expression.

HTH,
Paul.

Re: About Question enthuware.ocajp.i.v8.2.1473 :

Posted: Tue Jul 21, 2015 10:36 am
by islam.amin099
I got it now. Thank you for the clarification.

Re: About Question enthuware.ocajp.i.v8.2.1473 :

Posted: Thu Mar 18, 2021 12:41 am
by articulatesnail

Code: Select all

checkList(new ArrayList(), al -> al.isEmpty());
Then for this statement (correct answer), is the al passed in "auto-widened" to List?

Re: About Question enthuware.ocajp.i.v8.2.1473 :

Posted: Thu Mar 18, 2021 4:30 am
by admin
No, the question of al being auto-widened does not arise because al is not a preexisting variable. al is a new variable for this scope and its type is List.
Think of the lambda expression al->al.isEmpty() like this:

Code: Select all

class SomeClass implements Predicate<List>{
  public boolean test(List al){  <-- The type of al is interpreted by the compiler to be List
   al.isEmpty();
  }
}