Oscar Lundberg Oscar Lundberg - 21 days ago 6
Java Question

Get class from ArrayList

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

Answer

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;
    ...
}