R
Red Orchid
JDK 5.0 supports 'Generics' feature. But,
the following code generates compile error.
===================================
public class CircularBuffer<E> {
E[] buf;
int head;
int tail;
public CircularBuffer(int capacity) {
buf = new E[capacity]; // #1
}
...
}
====================================
The error is #1.
What reason that java compiler writers make the
'Generics' feature as the above ?
The 'Generics' of java do not support primitive type.
Therefore, java compiler can not confuse primitive
type and object type. Why is not the above code
compiled in java ?
The class 'ArrayList<E>' of java has the following code.
====================================================
....
this.elementData = (E[])new Object[initialCapacity]; // #2
....
====================================================
The one of purposes of using 'Generics' is type safety
in addition to reducing coding efforts and etc.
The above #2 tries casting super type to sub type if 'E'
is not 'Object' type. #2 looks like an ugly statement.
Of course,
it may be that one insist on #2's type safety by reason
that 'E' is treated as 'Object' inside 'ArrayList<E>'.
But, I think that #1 is beter than #2.
What your opinion?
the following code generates compile error.
===================================
public class CircularBuffer<E> {
E[] buf;
int head;
int tail;
public CircularBuffer(int capacity) {
buf = new E[capacity]; // #1
}
...
}
====================================
The error is #1.
What reason that java compiler writers make the
'Generics' feature as the above ?
The 'Generics' of java do not support primitive type.
Therefore, java compiler can not confuse primitive
type and object type. Why is not the above code
compiled in java ?
The class 'ArrayList<E>' of java has the following code.
====================================================
....
this.elementData = (E[])new Object[initialCapacity]; // #2
....
====================================================
The one of purposes of using 'Generics' is type safety
in addition to reducing coding efforts and etc.
The above #2 tries casting super type to sub type if 'E'
is not 'Object' type. #2 looks like an ugly statement.
Of course,
it may be that one insist on #2's type safety by reason
that 'E' is treated as 'Object' inside 'ArrayList<E>'.
But, I think that #1 is beter than #2.
What your opinion?