Item 26: Favor generic types

1.  Generic types are safer and easier to use than types that require casts in client code. When you design new types, make sure that they can be used without such casts. This will often mean making the types generic.

 

2.  The way to eliminate the generic array creation error is to create an array of Object and cast it to the generic array type. The second way is to define your field/variable as Object array instead of generic array, and cast the array elements to the generic type when reading them from the array. It is riskier to suppress an unchecked cast to an array type than to a scalar type, which would suggest the second solution. But in a realistic generic class, you would probably be reading from the array at many points in the code, so choosing the second solution would require many casts to E rather than a single cast to E[], which is why the first solution is used more commonly.

 

3.  The type parameter list (<E extends Delayed>) requires that the actual type parameter E must be a subtype of java.util.concurrent.Delayed. This allows the DelayQueue implementation and its clients to take advantage of Delayed methods on the elements of a DelayQueue, without the need for explicit casting or the risk of a ClassCastException. The type parameter E is known as a bounded type parameter.

 

你可能感兴趣的:(generic type)