I
Ian Wilson
I don't see how to elegantly satisfy toArray(T[] a) in an abstract class.
The code below works but I'd rather avoid the need for the setType()
which instantiates an T[] for .toArray(). Obviously I cant instantiate
an T[] in the abstract class.
Is there a better way?
----------------------------------------------------
import java.util.ArrayList;
public class ArrayListProblem {
public static void main(String[] args) {
FooModel model = new FooModel();
String[] fooCodes = model.getCodes();
for(int i = 0; i<fooCodes.length; i++) {
System.out.println(fooCodes);
}
}
}
abstract class AbstractCodeModel<T> {
private ArrayList<T> codes = new ArrayList<T>();
private T[] type;
void addCode(T item) {
codes.add(item);
}
void setType(T[] t) {
this.type = t;
}
public T[] getCodes() {
return codes.toArray(type);
}
}
class FooModel extends AbstractCodeModel<String> {
FooModel() {
setType(new String[0]);
addCode("A");
addCode("B");
}
}
The code below works but I'd rather avoid the need for the setType()
which instantiates an T[] for .toArray(). Obviously I cant instantiate
an T[] in the abstract class.
Is there a better way?
----------------------------------------------------
import java.util.ArrayList;
public class ArrayListProblem {
public static void main(String[] args) {
FooModel model = new FooModel();
String[] fooCodes = model.getCodes();
for(int i = 0; i<fooCodes.length; i++) {
System.out.println(fooCodes);
}
}
}
abstract class AbstractCodeModel<T> {
private ArrayList<T> codes = new ArrayList<T>();
private T[] type;
void addCode(T item) {
codes.add(item);
}
void setType(T[] t) {
this.type = t;
}
public T[] getCodes() {
return codes.toArray(type);
}
}
class FooModel extends AbstractCodeModel<String> {
FooModel() {
setType(new String[0]);
addCode("A");
addCode("B");
}
}