EDIT: For anyone stumbling upon this in the future, OHGODSPIDERS phrased the question better in the comments, saying, "His intention is to change the method toArray to public T[] toArray() which will throw an error because the method toArray() of List returns an Object[]". the issue is that java does not let you (without workarounds) create Arrays of generic types (e.g. T).
So I am trying to implement a method in a class that returns an Array representation of the data contained (it is for an assignment to practice binary search trees). This is the relevant code (I think):
public ArrayList<T> toArrayList() {
// TODO Auto-generated method stub.
return this.root.toArrayList();
}
public Object[] toArray() {
// TODO Auto-generated method stub.
return this.toArrayList().toArray();
}
Note specifically the return type of the toArray()
method. I am trying to figure out why when I set the return type to T[]
instead Eclipse gets mad and throws an error. I think that it makes more sense though for it to be T. Both the toArrayList()
and toArray()
methods pass the provided unit tests as written.
Thank you in advance for your help! Please let me know if there is anything I can clarify. I know this is a basic question but this is the first time in my coding career Google hasn't had a good answer for me!
I posted the following as a comment but I figured I would put it here as well so I can copy my new code too: (If this is discouraged please let me know and I will make whatever changes suggested):
@OHGODSPIDERS exactly. Sorry I was not clearer. I read through the links and I think I understand now that I should use the toArray(T[] a) version instead. However, when I try to do that Eclipse says I can't create a generic array. However, isn't that exactly what the method says to do?
public T[] toArray(){
return this.toArrayList().toArray(new T[0]);
}