Not allowed E[] buf = new E[5]; ... ?

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?
 
M

Mike Schilling

Red Orchid said:
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.

Why in the world do you not give the text of the error?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top