Goal
I am making a Java class that will give enhanced usability to arrays, such as add, remove, and contains methods. I figured the best solution is to make a class (called ArrayPP) that has a type parameter T. This way, the user can interact with the ArrayPP object as easily as they can with an array of the same type.
Problem
I quickly found that such methods as add will require the creation of a separate array, and end up changing the target array t from an array of Ts into an array of Objects. As you may guess, this totally destroys the usability, and when I try to do something like
File[] f = new File[0];
ArrayPP<File> appF = new ArrayPP(f);
appF.add(saveFile);
f = appF.toArray();
the program throws
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.io.File;
because the add method has to change the array into an array of Objects, as the Java compiler won't let you make a generic array (T[] t = new T[0]; is bad, but T[] t = (T[]) new Object[0]; is okay). I know from line-by-line debugging that the above code keeps the array t, in this case, as a n array of Files UNTIL the 4th line of the add method is called. Does anyone have a solution that will keep the array t being an array of Ts and not an array of Objects?
Sample Code
Below is a VERY watered-down version of my class.
public class ArrayPP<T>
{
T[] t;
/**
* Creates a new Array++ to manage the given array.
* <h3>Analogy:</h3>
* <tt>ArrayPP<String> s = new ArrayPP(args);</tt><br/>
* is analogous to<br/>
* <tt>String s[] = args;</tt>
* @param array The array to be managed
*/
public ArrayPP(T[] array)
{
t = array;
}
/**
* Appends a value to the end of the array
* @param val the value to be appended
* @return the resulting array.
*/
public ArrayPP add(T val)
{
T[] temp = (T[]) new Object[t.length + 1];
System.arraycopy(t, 0, temp, 0, t.length);
temp[temp.length - 1] = val;
t = (T[])temp;
return this;
}
/**
* Returns the array at the core of this wrapper
* @return the array at the core of this wrapper
*/
public T[] toArray()
{
return t;
}
}
Possible Solution?
After looking at other questions about generic arrays, I think I have a solution:
Instead of
/**
* Appends a value to the end of the array
* @param val the value to be appended
* @return the resulting array.
*/
public ArrayPP add(T val)
{
T[] temp = (T[]) new Object[t.length + 1];
System.arraycopy(t, 0, temp, 0, t.length);
temp[temp.length - 1] = val;
t = (T[])temp;
return this;
}
will this work?
/**
* Appends a value to the end of the array
* @param val the value to be appended
* @return the resulting array.
*/
public ArrayPP<T> add(T val)
{
t = java.util.Arrays.copyOf(t, t.length + 1);
t[t.length - 1] = val;
return this;
}
java.util.ArrayList.ArrayListhave that you need? Can't you just create a class that extendsArrayList?