[Java.lang.String; cannot be added to java.lang.String

I get a vector from the product API.

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

The vector is expected to contain strings as a value. I can print the vector size as 2. But for some reason I cannot repeat and print the values.

I tried

 Iterator<?> iter = dataVector.iterator(); while( iter.hasNext()) { System.out.println(iter.next()); } 

I always get

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

I used

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

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

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

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

If the vector contains java.lang.String , why am I getting this exception? How to print the actual values?

Please provide your suggestions.

+6
source share
3 answers

Thus, the API does not return a row vector, but a row vector [].

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

 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]); } } 
+7
source

Try comparing their classLoaders. If they are different, then this exception occurs.

 StringClass1.getClassLoader()==StringClass2.getClassLoader(); 
+4
source

No need to use an iterator. You can simply use the elementAt(index) Vector method to print the values. Use the For loop to get Vector indices.

Example:

 Vector<?> dataVector = dataAPI.getReturnVector(); for(int i = 0; i < dataVector.size(); i++) { System.out.println(dataVector.elementAt(i)); } 

If you get a strange answer (numbers and letters), you get a String[] object. This means that you will use the Arrays built-in method to print the String[] array. See comments below.

+1
source

Source: https://habr.com/ru/post/907403/


All Articles