[java.lang.String; cannot be cast to java.lang.String

jobinbasani picture jobinbasani · Feb 1, 2012 · Viewed 41.3k times · Source

I'm obtaining a Vector from a product's API.

Vector<?> dataVector = dataAPI.getReturnVector();

The vector is expected to contain Strings as value. I'm able to print the size of the vector as 2. But for some reason I'm not able to iterate and print the values.

I tried

Iterator<?> iter = dataVector.iterator();

while( iter.hasNext()) {
    System.out.println(iter.next());
}

I always end up getting a

[java.lang.String; cannot be cast to java.lang.String

I used

iter.next().getClass().getName() 

and it turned out to be java.lang.String only.

I googled a bit and found a similar problem at http://prideafrica.blogspot.com/2007/01/javalangclasscastexception.html

I tried to set the generics as String[], but ended up with the same error.

If the vector contains java.lang.String, why do I get this cast exception? How can I print the actual values?

Kindly provide your suggestions.

Answer

Peter Jamieson picture Peter Jamieson · Feb 1, 2012

So the API is not returning a Vector of Strings but a Vector of String[].

You should be able to iterate through the vector and then, for each element, loop through the array.

Iterator<String[]> iter = dataVector.iterator();

while( iter.hasNext()) {
    String[] array = iter.next();
    for(int i=0; i < array.length; i++)
    {
       System.out.println(i + ": " + array[i]);
    }
}