Oscar Lundberg
Oscar Lundberg

Reputation: 433

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

Upvotes: 1

Views: 5206

Answers (2)

duckstep
duckstep

Reputation: 1138

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

Upvotes: 2

larsgrefer
larsgrefer

Reputation: 2853

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>

Upvotes: 1

Related Questions