You are not logged in.

  • Login

Dear visitor, welcome to Coder Forum. If this is your first visit here, please read the Help. It explains in detail how this page works. To use all features of this page, you should consider registering. Please use the registration form, to register here or read more information about the registration process. If you are already registered, please login here.

1

Tuesday, October 16th 2007, 6:49pm

ArrayList -> Array in Typ

Hallo, ich habe eine kleine ArrayList, die ich mit Parts des Apache Jakarta Projekts füttere:

Java Quellcode

1
2
3
ArrayList<Part> al = new ArrayList<Part>();
al.add(new StringPart("key11", "var1"));
al.add(new StringPart("key12", "var2"));


Nun brauche ich aber das Part[]-Array - Also hab ich versuch mittels

Java Quellcode

1
((Part[])al.toArray());


den Array zu holen, was mir mit folgender Fehlermeldung verweigert wird:

Quoted


Exception in thread "Thread-5" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Lorg.apache.commons.httpclient.methods.multipart.Part;


Wie komme ich nun an das Part[]-Array?

2

Tuesday, October 16th 2007, 9:29pm

toArray akzeptiert den Casting Typ als Parameter.

Auswendig weiß ich es nicht mehr hunderprozentig. Probiers mal aus:

Java Quellcode

1
al.toArray(new Part[0]));

3

Wednesday, October 17th 2007, 2:46am

Super, das funktioniert! Danke! Aber sollte man nicht meinen, dass durch die Genercisangabe, Java wissen sollte, was für ein Array-Typ das zurückgegeben werden sollte...?!

4

Thursday, October 18th 2007, 11:10pm

Die andere Variante die immer funktioniert, geht über die Array Klasse:

Java Quellcode

1
2
3
4
5
@SuppressWarnings ("unchecked")
  public <T> T [] createGenericArray (final Class <T> aClass, final int nLength)
  {
	return (T []) Array.newInstance (aClass, nLength);
  }

Dort hast du zwar auch einen Cast, aber der funktioniert :)

Similar threads

Social bookmarks