?
Solved

Accessing Methods of Objects in ArrayLists

Posted on 2010-04-02
2
Medium Priority
?
176 Views
Last Modified: 2013-11-23
I am still fairly new to Java and I'm trying to understand Array Lists better. If you create an Array List and put objects within the Array List, how can you access the methods of the object?

For example, the code below is just a simple Book class. If I were to write this code:

   ArrayList booksList = new ArrayList();
   Book myBook = new Book();
   booksList.add(myBook);

How would I access the getAuthor method of myBook?
public class Book
{
     public string Author;
     public string Title;
     
     public String getAuthor() {
       return Author;
     }
}

Open in new window

0
Comment
Question by:spoggles
2 Comments
 
LVL 92

Accepted Solution

by:
objects earned 1400 total points
ID: 29514807
  ArrayList booksList = new ArrayList();
   Book myBook = new Book();
   booksList.add(myBook);

   // get author of first (java indexes are 0-based) book in list

   String author = booksList.get(0).getAuthor();
0
 
LVL 8

Assisted Solution

by:Arabia_vn
Arabia_vn earned 600 total points
ID: 29515041
Get the object in the ArrayList and call it's method
((Book)booksList.get(0)).getAuthor()
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Suggested Courses
Course of the Month7 days, 4 hours left to enroll

593 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question