반응형
Questions and Exercises: Generics
- 특정 property (예, odd integers, prime numbers, palindromes)을 갖고 있는 collection내 엘리먼트의 수를 계산하기 위하여 제네릭 메소드를 작성하시오.
Write a generic method to count the number of elements in a collection that have a specific property (for example, odd integers, prime numbers, palindromes). 다음 클래스는 컴파일됩니까? 안된다면 그 이유는?
Will the following class compile? If not, why?public final class Algorithm { public static <T> T max(T x, T y) { return x > y ? x : y; } }
- Write a generic method to exchange the positions of two different elements in an array.
- 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(); }
- Write a generic method to find the maximal element in the range [begin, end) of a list.
- 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; }
- Given the following classes:Will the following code compile? If not, why?
class Shape { /* ... */ } class Circle extends Shape { /* ... */ } class Rectangle extends Shape { /* ... */ } class Node<T> { /* ... */ }
Node<Circle> nc = new Node<>(); Node<Shape> ns = nc;
- Consider this class:Will the following code compile? If not, why?
class Node<T> implements Comparable<T> { public int compareTo(T obj) { /* ... */ } // ... }
Node<String> node = new Node<>(); Comparable<String> comp = node;
- How do you invoke the following method to find the first integer in a list that is relatively prime to a list of specified integers?Note that two integers a and b are relatively prime if gcd(a, b) = 1, where gcd is short for greatest common divisor.
public static <T> int findFirst(List<T> list, int begin, int end, UnaryPredicate<T> p)
반응형
'Java 배우기' 카테고리의 다른 글
Creating and Using Packages 패키지 만들기와 사용하기 (0) | 2016.01.24 |
---|---|
Lesson: Packages 단원: 패키지 (0) | 2016.01.24 |
Restrictions on Generics (0) | 2016.01.24 |
Non-Reifiable Types (0) | 2016.01.24 |
Effects of Type Erasure and Bridge Methods (0) | 2016.01.24 |
댓글