I am writing a java application that requires a generic list. This list needs to be capable of being resized dynamically and fairly often, the obvious answer for this would be a generic Linkedlist
. Unfortunately, it also needs to get/set values just as frequently as it adds/removes them via calling an index. This would be solved rather nicely by an Arraylist
. Since both of these options weren't quite what I was looking for I created my own generic array wrapper class. I have known for quite some time that it is illegal in java to create a generic array, and I have read that typically instead of using generics to define the type of your array, one would just create an object[]
array and then cast each element individually to the proper type. This is similar to what Arraylist
already does; however, I have read that casting is a very expensive operation in java. So, to get around the necessity of casting, my custom wrapper class looks something like this.
public abstract class CustomArrayWrapper<E extends Object>{
private E[] content;
public abstract E[] empty(int n);
public CustomArrayWrapper(){
this.content = empty(0);
}
public CustomArrayWrapper(int n){
this.content = empty(n);
}
public CustomArrayWrapper(E[] content){
this.content = content;
}
public E[] content(){
return content;
}
}
This is just the bare bones of the class, but the main idea, is that each specific use of the array wrapper extends the empty(int n)
method, returning an array of size n that is of type E
hopefully avoiding all of that expensive casting. An example is as follows using String
as the type.
public class StringArrayWrapper extends CustomArrayWrapper<String>{
public StringArrayWrapper(){
super();
}
public StringArrayWrapper(int n){
super(n);
}
public StringArrayWrapper(String[] content){
super(content);
}
public String[] empty(int n){
return new String[n];
}
}
I know that this implementation works, what I don't know is
- Is this safe to implement?
- I know casting is a little finicky as there is a lot of implicit casting built into java, is this actually a way to get around all of the casting that an
Arraylist
already performs? - Is it more/less efficient than casting every element to the proper type as in an
ArrayList
?