0

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?

2
  • Could you post your code? Commented Feb 16, 2014 at 20:18
  • Is your array list typed? Commented Feb 16, 2014 at 20:26

3 Answers 3

1

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());
Sign up to request clarification or add additional context in comments.

Comments

0

Define pupils as:

List<Pupil> pupils = ...(some initialization)

or cast it to Pupil:

System.out.println(((Pupil)(pupils.get(1))).getName())

Comments

0

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())
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.