Generics Quiz 1
The quiz below tests your knowledge of the material learnt in Generics - Lesson 2 - Raw/Generic Type Comparison.
Question 1 : What will the compiler do with the following code private static final List names = new ArrayList();
- The code compiles but with warning messages for raw types and unchecked calls.
Question 2 : Which is the preferred syntax?
- <code>private static final List<String> names = new ArrayList<>();</code> is preferred as it uses the diamond operator which answer B does not. Answer C uses a raw type and is unsafe.
Question 3 : What happens when we try to compile the following class?
package com.server2client;
import java.util.*;
public class RawTypeNameCollection {
private static final List<String> names = new ArrayList<>();
public static void main (String[] args) {
names.add("Bill");
names.add("Ben");
names.add(6);
}
}
- The code will not compile as the compiler stops the <code>int</code> from being put into the <code>String</code> collection.
Question 4 : We can mix raw types and generics
- We CAN mix raw types and generics although this is in no way recommended as it can lead to unsafe code and runtime exceptions.
Question 5 : What happens when we try to compile the following class?
package com.server2client;
import java.util.*;
public class RawTypeNameCollection {
private static final List<String> names = new ArrayList<>();
public static void main (String[] args) {
names.add("Bill");
names.add("Ben");
names.add("6");
}
}
- The code compiles normally as we are just putting <code>String</code> objects into a <code>String</code> collection.
Question 6 : Which of the following syntax will compile?
private static final List<String> names = new ArrayList<>(); //1
private static final List<String> names = new ArrayList<String>(); //2
private static final List<String> names = new ArrayList(); //3
- All the syntax is valid although answer B does not use the diamond operator and answer C uses a raw type and is unsafe.
Quiz Progress Bar Please select an answer
What's Next?
In the next quiz we test your knowledge of generic interfaces.