Campbell Ritchie wrote:
What array? You cannot insert elements into an array because its size is fixed. I presume you mean a List of some sort. Please be careful about nomenclature.Thomas Roth wrote:. . . Array would be . . . when it is inserted. . . .
Stephan van Hulst wrote:I don't have the book in question, but could it be that before insertion, "pig" is referred to as "second element" because "123" might be referred to as "zeroth element"?
Remember, arrays in Java are 0-based.
Stephan van Hulst wrote:The way Java performs type inference on lambda expressions is very complex and will take a long time to explain. The short answer is that in the first case, you explicitly told the compiler to use the length() method of the String class, while in the second case, the compiler has to infer that you want to use the String class. Part of the reason why the compiler is not able to infer that you want to use String, is because comparing() takes a generic type with a parameter that has a lower bound. So when you write Comparator.comparing(s -> s.length()), the compiler interprets that as Comparator.comparing((Object s) -> s.length()). As you know, Object doesn't have a length() method. The compiler does not look at the surrounding method call to provide the comparing() method with more context.
You can fix this by explicitly stating the type of the lambda argument, or by passing the generic type arguments to the comparing() method explicitly:
Jeanne Boyarsky wrote:No. Oracle has a disclaimer that you should assume the necessary context:
Code fragments: A code fragment is a small section of source code that is presented without its context. Assume that all necessary supporting code exists and that the supporting environment fully supports the correct compilation and execution of the code shown and its omitted environment.
This means if the code isn't in a method, you can assume it declares any checked exceptions. You will see this technique on the real exam too so glad it came up here!