원문 번역중입니다.

원문 : http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html


당신이 Cellction 에서 element를 취할 때, 당신은 Collection 안에 저장되어있는 element로 타입을 캐스팅해야만 한다. 게다가 더 불편한것은, 이것은 위험하다는 것이다. 컴파일러는 당신이 Collection 타입을 동일하게 캐스팅했는데 체크하지 않으며, 따라서 런타임시에 캐스팅은 실패할 수 있다.

Generics 은 당신이 컴파일러에게 Collection의 타입에 대해 전할 수 있는 방법을 제공한다. 따라서 이것은 컴파일러에 의해 체크될 것이다. 한번에 컴파일러는 Collection의 타입을 알며, 당신이 Collection에 저장하거나 취할 때 올바른 캐스팅을 하고 있는지 체크할 수 있다.


여기에 Collection 튜토리얼로부터 얻은 간단한 예제가 있다.

// Removes 4-letter words from c. Elements must be strings
static void expurgate(Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); )
if (((String) i.next()).length() == 4)
i.remove();
}


여기에 generic을 사용한 수정된 예제가 있다.

// Removes the 4-letter words from c
static void expurgate(Collection<String> c) {
for (Iterator<String> i = c.iterator(); i.hasNext(); )
if (i.next().length() == 4)
i.remove();
}

당신이 <Type> 코드를 보게 될 때, 이것은 "of Type"으로 읽는다. 위에 정의는 "Collection of String c"로 읽는다. generics를 사용한 코드는 더 깨끗하며 더 안전한다. We have eliminated an unsafe cast and a number of extra parentheses. More importantly, we have moved part of the specification of the method from a comment to its signature, so the compiler can verify at compile time that the type constraints are not violated at run time. Because the program compiles without warnings, we can state with certainty that it will not throw a ClassCastException at run time. The net effect of using generics, especially in large programs, is improved readability and robustness.

To paraphrase Generics Specification Lead Gilad Bracha, when we declare c to be of type Collection<String>, this tells us something about the variable c that holds true wherever and whenever it is used, and the compiler guarantees it (assuming the program compiles without warnings). A cast, on the other hand, tells us something the programmer thinks is true at a single point in the code, and the VM checks whether the programmer is right only at run time.

generics의 주된 사용은 Collection 이지만, 여기에는 다른 많은 사용법이 있다. “Holder classes,” such as WeakReference and ThreadLocal, have all been generified, that is, they have been retrofitted to make use of generics. More surprisingly, class Class has been generified. Class literals now function as type tokens, providing both run-time and compile-time type information. This enables a style of static factories exemplified by the getAnnotation method in the new AnnotatedElement interface:

    <T extends Annotation> T getAnnotation(Class<T> annotationType); 
This is a generic method. It infers the value of its type parameter T from its argument, and returns an appropriate instance of T, as illustrated by the following snippet:
    Author a = Othello.class.getAnnotation(Author.class);
Prior to generics, you would have had to cast the result to Author. Also you would have had no way to make the compiler check that the actual parameter represented a subclass of Annotation.

Generics are implemented by type erasure: generic type information is present only at compile time, after which it is erased by the compiler. The main advantage of this approach is that it provides total interoperability between generic code and legacy code that uses non-parameterized types (which are technically known as raw types). The main disadvantages are that parameter type information is not available at run time, and that automatically generated casts may fail when interoperating with ill-behaved legacy code. There is, however, a way to achieve guaranteed run-time type safety for generic collections even when interoperating with ill-behaved legacy code.

The java.util.Collections class has been outfitted with wrapper classes that provide guaranteed run-time type safety. They are similar in structure to the synchronized and unmodifiable wrappers. These “checked collection wrappers” are very useful for debugging. Suppose you have a set of strings, s, into which some legacy code is mysteriously inserting an integer. Without the wrapper, you will not find out about the problem until you read the problem element from the set, and an automatically generated cast to String fails. At this point, it is too late to determine the source of the problem. If, however, you replace the declaration:

    Set<String> s = new HashSet<String>();
with this declaration:
    Set<String> s = Collections.checkedSet(new HashSet<String>(), String.class);
the collection will throw a ClassCastException at the point where the legacy code attempts to insert the integer. The resulting stack trace will allow you to diagnose and repair the problem.

당신이 할 수 있는 모든 곳에서 generics를 사용할 수 있다. The extra effort in generifying code is well worth the gains in clarity and type safety. It is straightforward to use a generic library, but it requires some expertise to write a generic library, or to generify an existing library. There is one caveat: You may not use generics (or any other Tiger features) if you intend to deploy the compiled code on a pre-5.0 virtual machine.

If you are familiar with C++'s template mechanism, you might think that generics are similar, but the similarity is superficial. Generics do not generate a new class for each specialization, nor do they permit “template metaprogramming.”

generics 에 대해 좀 더 많은걸 배우고 싶다면  Generics Tutorial 여기를 보라.

+ Recent posts