PDA

View Full Version : Java - generic Array



LKjell
January 3rd, 2010, 01:16 PM
Since I cannot create generic array because of some type safety how can I then create an array for example in toArray() method?

PaulM1985
January 3rd, 2010, 01:32 PM
Creating a generic array? Do you mean you want to create an array of a specific type, or do you want to create an array of all types? So for example do you want an array of Cat objects or an array of any type of Object.

There are generic arrays that can be used for creating an array of a type. Look up ArrayList on the Java API.

If you want an array to store Object 's of various types... why would you want to do this?

Paul

NovaAesa
January 3rd, 2010, 03:18 PM
I think LKjell means that you cannot create an array of say List<MyObj>. (which of course you can't - obvious type safety issues there). I'm not really sure what JKjell's actual question is though!

Reiger
January 3rd, 2010, 04:49 PM
Uhm?



public Type[] fromCollection(Collection<Type> collected) {
/* see the docs at: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collection.html */
return collected.toArray(new Type[] {});
}

LKjell
January 3rd, 2010, 09:37 PM
Say I have


public class list<E extends Comparable<E>> implements mylist<E> {

...

public E[] toArray(E[] a) {
E b[] = new E[size]; //Error: generic array
...
}
}

Reiger
January 4th, 2010, 05:09 AM
Since your E is-a Comparable:



public E[] toArray(E[] a) {
Comparable [] my_array = new Comparable[size]; // use supertype
/* code */
return (E[]) my_array; // cast to return type.
}

LKjell
January 4th, 2010, 07:26 AM
Thanks Reiger I was pulling my hair when I was one error reading "Found E required E".