Consider the simple stack implementation of article 6th:
Public classStack {pprivate object[] elements; Private intSize = 0; Private Static Final intDefault_inital_capacity = 16; PublicStack () {Elements=NewObject[default_inital_capacity]; } Public voidpush (Object e) {ensurecapacity (); Elements[size++] =e; } PublicObject Pop () {if(Size = = 0) { Throw Newemptystackexception (); } Object result= elements[--size]; Elements[size]=NULL; returnresult; } Public BooleanIsEmpty () {returnSize = = 0; } Private voidensurecapacity () {if(Elements.length = =size) Elements= arrays.copyof (Elements, 2 * size + 1); }}
Generics in this class can increase the security of the type and are easy for clients to use (no explicit cast type required)
First replace all object types with the type parameter:
Public classStack<e>{pprivate e[] elements; Private intSize = 0; Private Static Final intDefault_inital_capacity = 16; PublicStack () {Elements=NewE[default_inital_capacity]; } Public voidpush (e e) {ensurecapacity (); Elements[size++] =e; } PublicE Pop () {if(Size = = 0) { Throw Newemptystackexception (); } E result= elements[--size]; Elements[size]=NULL; returnresult; } Public BooleanIsEmpty () {returnSize = = 0; } Private voidensurecapacity () {if(Elements.length = =size) Elements= arrays.copyof (Elements, 2 * size + 1); }}
Because you cannot create an array of non-materialized types, all errors (new E[default) Initial_cap] are not allowed)
Workaround:
1. Create an object array and convert it to a generic array type:
New Object[default_initial_capacity];
The error becomes a warning, because type safety is guaranteed, so you can ignore the warning with the supresswarning comment.
2. Change the type of elements field from e[] to object[]:
Private Object[] elements;
E result = (e) elements[--size];
Generates a warning, because type safety is guaranteed, so you can ignore the warning with the supresswarning comment.
In practice, the second method is more, because pop methods are often called, and frequent type conversions can be time consuming.
In 25, it is encouraged to use lists rather than arrays. In fact, the list is not always used in generics. To improve performance, the list is not a basic implementation provided by Java, such as ArrayList, which needs to be implemented on an array, while some classes, such as HashMap, are implemented on the array to improve performance.
26th: Preferential consideration of generics