user3316766
user3316766

Reputation: 1

Accessing information about objects in an array list

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

Answers (3)

Reut Sharabani
Reut Sharabani

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

Maxim
Maxim

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

Mureinik
Mureinik

Reputation: 312289

Generics should do the trick. If you define pupils as a types list, then get(int) should return a Pupil object:

List<Pupil> pupils = new ArrayList<Pupil>();
// add some data to the list
System.out.println(pupils.get(1).getName());

Upvotes: 1

Related Questions