Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 516
jobinbasani Avatar asked Feb 01 '12 15:02

jobinbasani


1 Answers

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]);
    }
}
like image 192
Peter Jamieson Avatar answered Oct 27 '22 04:10

Peter Jamieson