Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing specific object fields from an ArrayList

Suppose we create an listOfObjects of type ArrayList, which contains objects of type Object:

 public static ArrayList listOfObjects = new ArrayList();

We have an Object constructor, which creates an Object with two fields, name and type:

public Object(String name, int type) { /*some code*/ }

Now we create two Objects, then add them to listOfObjects:

public static Object object1 = new Object("object one", 1);
public static Object object2 = new Object("object two", 2);
listOfObjects.add(object1);
listOfObjects.add(object2);

Assuming that object1 and object2 were correctly added to listOfObjects, how can we access the type field of an object in the list?

I have tried

listOfObjects.get(1).type;

but that doesn't seem to work. Is there a way to do this?

EDIT Object is an example name.

like image 558
tkl1234567890 Avatar asked Jun 22 '26 18:06

tkl1234567890


1 Answers

  1. It's a really bad idea to define a class called Object, since there is already a class called java.lang.Object, and since it's in the java.lang package, all your sources implicitly import it.
  2. You need to make your field public - public int type;, if you want to access it the way, you posted.
  3. It's also not a good idea, to leave fields public, so make public getters for them: public int getType() { return type; }
like image 196
Balázs Édes Avatar answered Jun 25 '26 06:06

Balázs Édes