wdwd dsd
wdwd dsd

Reputation: 25

converting from Object to string in java

I have this below method

public List<Object> ProductbyJobcode (String jobcode)
{
    List<Object> temp = new ArrayList<Object>();
    temp = riskJobCodeProductMappingDAO.fetchProductByJobCode(jobcode);
    return temp;
}

and i am taking the input in the Object list from the above method into Object type of list

List<Object> temp = new ArrayList<Object>() ;
temp = ProductbyJobcode(jobcode);

now i am trying to retrieve the value into string but i am getting exception, please advise how to achieve the same how i will convert the object to string

String Product ;
String Actiontype;

for (int i = 0; i < temp.size(); i++) {
    product = temp.get(0).toString();
    Actiontype = temp.get(1).toString();
}

Upvotes: 1

Views: 124

Answers (3)

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

Object.toString() could provide NPE. So more suitable method is String.valueOf().

String Product = temp.size() >= 1 ? String.valueOf(temp.get(0)) : null;
String Actiontype = temp.size() >= 2 ? String.valueOf(temp.get(1)) : null;

Upvotes: 1

Rafał Sokalski
Rafał Sokalski

Reputation: 2007

The problem is that if your temp list contains only 1 element you try to get second element in this line:

Actiontype = temp.get(1).toString();

That cause:

java.lang.IndexOutOfBoundsException

Because you try to get second element when the list contains only one

Upvotes: 0

daniu
daniu

Reputation: 14999

Well this

for (int i = 0; i < temp.size(); i++) {
    product = temp.get(0).toString();
    Actiontype = temp.get(1).toString();
}

doesn't really test the bounds of the list correctly; you might only have one String in the list, which will mean temp.get(1) throws an IndexOutOfBoundsException.

It's not clear what exactly you're trying to achive, but this should work:

for (int i = 0; < temp.size; i++) {
    System.out.println(temp.get(0));
}

If you really need the two items, you probably want something like this

product = (temp.isEmpty()) ? null : temp.get(0).toString();
actionType = (temp.size() > 1) ? temp.get(1).toString() : null;

Upvotes: 0

Related Questions