Eme Emertana
Eme Emertana

Reputation: 571

How to access to a method of an object that is in a list

Hi I have a list of objects,

 myclass obj1 = new myclass();
 myclass obj2 = new myclass();
 obj1.name("hello");
 obj2.name("bye");
 List objectsList = new ArrayList
 objectsList.add(obj1);
 objectsList.add(obj2);

how can I access to methods of each object in the list? I have tried the following but I dont have access to methods.

Object obj = objectsList.get(1);
obj. <<< no access to methods           

Upvotes: 0

Views: 101

Answers (3)

apalopohapa
apalopohapa

Reputation: 185

One way, given how you've coded it, is to cast the objects as myclass, since the Object class does not define such methods.

Upvotes: 0

Seitaridis
Seitaridis

Reputation: 4529

You need to cast them to myclass.

((myclass) obj).methodOfMyClass();

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500065

The code you've given won't even compile... but if you use generics then you'll end up with strongly-typed elements when you fetch:

// TODO: Use a better class name which obeys Java naming conventions
// Ditto name => setName
List<myclass> list = new ArrayList<myclass>();
list.add(obj1);
list.add(obj2);

...
myclass obj = list.get(1);
System.out.println(obj1.getName());

Upvotes: 9

Related Questions