1

I'm wondering how to change a variable inside an object in an ArrayList.

I have tried myList.get(i); but this returns an <Object> and I don't understand what to do this.

(Basically) What I have:

ArrayList list = new ArrayList();
Issue issue = new Issue();
list.add(issue);

What i want to access later, via the list:

issue.myString;

So to clarify, I have an instance of class Issue inside ArrayList list, and I want to change issue.myString

2
  • 1
    cast that object to Issue for example -> ((Issue)list.get(index)).myString Commented Nov 19, 2016 at 19:25
  • Lol... I thought I tried that but apparently I had just messed up the parentheses... Commented Nov 19, 2016 at 19:28

2 Answers 2

2

You have (at least) two options.

The list contains only issues

In that case, you can use a typed list:

List<Issue> list = new ArrayList<>();
Issue issue = new Issue();
list.add(issue);

This way, calls like list.get(i) will return an Issue.

The list contains issues and other non-issue objects

List list = new ArrayList();
Issue issue = new Issue();
list.add(issue);
Object object = new Object();
list.add(object);

In that case, you'll have to check if the object is an Issue first.

Object rawItem = list.get(i);
if(rawItem instanceof Issue) {
    Issue issue = (Issue) rawItem;
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

1

Use a typed list:

ArrayList<Issue> list = new ArrayList<>();
Issue issue = new Issue();
list.add(issue);

now list.get(i) will return <Issue> and not just <Object>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.