Reputation: 426
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?
Upvotes: 0
Views: 122
Reputation: 426
I resolved my problem by belwo code
byte[] groupedItemIdsArr = (byte[])objArr[4];
String groupedItemIds = new String(groupedItemIdsArr);
Upvotes: 0
Reputation: 44854
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
Upvotes: 0
Reputation: 1211
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]);
Upvotes: 1
Reputation: 1014
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
}
Upvotes: 0
Reputation: 5834
It looks like you are using arrays not Lists in which case you can use:
String groupedItemIds = java.util.Arrays.toString(objArr[4]);
Upvotes: 0
Reputation: 4659
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.
Upvotes: 0
Reputation: 2154
You could try:
String groupedItemIds = Arrays.asList( objArr[4] ).toString();
This will produce: groupedItemIds = "[1,2,3,4,5]"
Upvotes: 0
Reputation: 36304
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..
Upvotes: 0
Reputation: 68975
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.
Upvotes: 0