XRB’s Blog
Published in

XRB’s Blog

Java Quiz of the Day

Java quiz of the day (easy): what gives

Object[] a = new Integer[]{};
List<Object> b = new ArrayList<Integer>();

Response: we get an exception on the second line:

Type mismatch: cannot convert from ArrayList<Integer> to List<Object>

Arrays and Generics are not consistent. While for arrays, an array of some type is also an array of one of its parent types, the same is not true for Generics. If it was, we could construct weird things where we would get at most a runtime exception when trying to access items of a collection. See the following example:

class A{
void foo(List list) {
List otherList = list; // (A)
otherList.add(“hi”); // (B)
}
}
List list = new ArrayList();
list.add(5);
new A().foo(list);
for (Integer i : list) {
System.out.println(i.intValue()); // (C)
}

Here line (A) is not a legal assignment. If it was, then we could insert into our originally List a String on line (B). Then back from our method foo, we would get a runtime exception when processing the list on line (C). This problem was fixed for Generics, while similar problems exist for arrays.

--

--

--

Random thoughts of a Software Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Patrick Jayet

Patrick Jayet

Polyglot (FR, DE, EN, ES), polyglot programmer (Java, Groovy, Ruby, Swift, Objective-C, Scala, Python, O’Caml) polyglot methodologist (Scrum, Kanban, Lean).

More from Medium

Pt 2. How to scan viruses in uploaded files in a Spring boot application using ClamAV Antivirus: A…

HOW TO CREATE YOUR FIRST MAVEN PROJECT

How to Chain Multiple Processors in Spring Batch?

Key Differences Between Spring Boot and Spring Framework