1

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();
}
7
  • 1
    Please look up and use proper Java naming conventions. Variables, fields and methods should be lowerCamelCase. It's confusing to read otherwise. Commented Jun 15, 2018 at 11:23
  • 3
    Which exception ? Commented Jun 15, 2018 at 11:24
  • 4
    What exception are you getting, and where? Commented Jun 15, 2018 at 11:24
  • 2
    1) For better help sooner, post a minimal reproducible example or Short, Self Contained, Correct Example. 2) Always copy/paste error and exception output! Commented Jun 15, 2018 at 11:26
  • 1
    What is the size of your temp list? Commented Jun 15, 2018 at 11:27

3 Answers 3

1

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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;

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.