␡
- Why Use Generics?
- Generic Types
- Generic Methods
- Bounded Type Parameters
- Generics, Inheritance, and Subtypes
- Type Inference
- Wildcards
- Type Erasure
- Restrictions on Generics
- Questions and Exercises: Generics
< Back
Page 10 of 10
This chapter is from the book
Questions and Exercises: Generics
Questions
- Will the following class compile? If not, why?
public final class Algorithm { public static T max(T x, T y) { return x > y ? x : y; } }
- If the compiler erases all type parameters at compile time, why should you use generics?
- What is the following class converted to after type erasure?
public class Pair<K, V> { public Pair(K key, V value) { this.key = key; this.value = value; } public K getKey(); { return key; } public V getValue(); { return value; } public void setKey(K key) { this.key = key; } public void setValue(V value) { this.value = value; } private K key; private V value; }
- What is the following method converted to after type erasure?
public static <T extends Comparable<T>> int findFirstGreaterThan(T[] at, T elem) { // . . . }
- Will the following method compile? If not, why?
public static void print(List<? extends Number> list) { for (Number n : list) System.out.print(n + " "); System.out.println(); }
- Will the following class compile? If not, why?
public class Singleton<T> { public static T getInstance() { if (instance == null) instance = new Singleton<T>(); return instance; } private static T instance = null; }
- Review the following classes:
class Shape { /* . . . */ } class Circle extends Shape { /* . . . */ } class Rectangle extends Shape { /* . . . */ } class Node<T> { /* . . . */ }
Will the following code compile? If not, why?
Node<Circle> nc = new Node<>(); Node<Shape> ns = nc;
- Consider this class:
class Node<T> implements Comparable<T> { public int compareTo(T obj) { /* . . . */ } // . . . }
Will the following code compile? If not, why?
Node<String> node = new Node<>(); Comparable<String> comp = node;
Exercises
- Write a generic method to count the number of elements in a collection that have a specific property (e.g., odd integers, prime numbers, palindromes).
- Write a generic method to exchange the positions of two different elements in an array.
- Write a generic method to find the maximal element in the range [begin, end] of a list.
Answers
You can find answers to these questions and exercises at http://docs.oracle.com/javase/tutorial/java/generics/QandE/generics-answers.html.
< Back
Page 10 of 10