简体   繁体   中英

convert object to string getting can not cast error

I have a list of object List in which at 4th index it has list of integer [1,2,3,4,5] Now I want to get list into a comma separated string. below is my try, but it giving error as can not cast.

for(Object[] objArr : relationshipInfo){
if(null != objArr[4]){
String groupedItemIds = (String)objArr[4];
}

how to do this?

Try the following:- use toString()

String output = relationshipInfo.toString();
output = output.replace("[", "");
output = output.replace("]", "");
System.out.println(output);


[UPDATE]

If you want fourth Object only then try:

    Object[] objArr = relationshipInfo.toArray();
    String groupedItemIds = String.valueOf(objArr[4]);

Integer Array or Integer can not be cast to a String.

try

for(Object[] objArr : relationshipInfo){
if(null != objArr[4]){
 String groupedItemIds =  new String (objArr[4]); // or String.valueOf(objArr[4]);
}

Update

If the 4th index is a Array then try

String groupedItemIds = Arrays.asList(objArr[4]).toString();

which will give you a comma delimitered String

You cannot cast an Object to an uncomatible type

for(Object[] objArr : relationshipInfo){
if(null != objArr[4]){
List<Integer> groupedItemIds = (List<Integer)objArr[4];;

//Loop over the integer list
}

You cannot type cast Object to String unless the Object is indeed a String. Instead you can do the following -

Call toString() on it. Override it in your class.

Try this :

for(Object[] objArr : relationshipInfo)
{
      if(null != objArr[4])
       {
          String groupedItemIds = String.valueOf(objArr[4]);
       }
}  

Ref :

public static String valueOf(Object obj)

Returns the string representation of the Object argument.
Link .

Difference between use of toString() and String.valueOf()

if you invoke toString() with a null object or null value, you'll get a NullPointerExcepection whereas using String.valueOf() you don't have to check for null value.

you want "comma separated string" . So, you iterate over the 4th index and read each integer and do "" + int1 +" , " + int2 etc.. you can do this (in) by overriding your toString() method..

You could try:

String groupedItemIds = Arrays.asList( objArr[4] ).toString();

This will produce: groupedItemIds = "[1,2,3,4,5]"

看起来您使用的是数组而不是列表,在这种情况下可以使用:

String groupedItemIds = java.util.Arrays.toString(objArr[4]);

I resolved my problem by belwo code

byte[] groupedItemIdsArr = (byte[])objArr[4];
String groupedItemIds = new String(groupedItemIdsArr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM