Reputation: 1
I have two classes, Teacher
and Pupil
. In the Teacher
class there is an array list of Pupil
's (containing instances of Pupil).
I'd like to do something like:
System.out.println(pupils.get(1).getName())
where getName
is a method from the Pupil
class. However, pupils.get(1)
does not seem to act as a Pupil
and won't let me call this method. How should I do it?
Upvotes: 0
Views: 44
Reputation: 31349
You should use Generics.
This assumes some basic stuff about your code. Specifically that pupils is a class containing pupil instances. That you can get them using getPupils() as a List/Collection.
ArrayList<Pupil> pupilsList = new ArrayList<Pupil>();
for (Pupil p : pupils.getPupils()){
// add all pupils
System.out.println("Adding " + pupilsList.add(p));
}
for (int i=0; i < pupilsList.size(); i++){
// print all pupils
System.out.println("Name: " + pupilsList.get(i).getName())
}
Upvotes: 0
Reputation: 339
Define pupils as:
List<Pupil> pupils = ...(some initialization)
or cast it to Pupil:
System.out.println(((Pupil)(pupils.get(1))).getName())
Upvotes: 0