Geole
Geole

Reputation: 376

Retrieve Values from a List within an Object

I'm trying to retrieve a value from an Object which sits within an ArrayList within another Object.

The basic structure is:

+++++

Book Object -> List of Author Objects -> Author Object -> Author first name variable

+++++

And I would like to access the first name of the first Author for a given Book

+++++

I have created a "Book" Class which looks like the following:

public class Book {

private String mTitle;

private List<Author> mAuthors;

public Book(String title, List<Author> authors) {
    this.mTitle = title;
    this.mAuthors = authors;
}

public String getmTitle() {
    return mTitle;
}

public List<Author> getmAuthors() {
    return mAuthors;
}
}

This class also contains a list of Author-Objects:

public class Author {

private String mFirstName;
private String mLastName;

public Author(String firstName, String lastName) {
    this.mFirstName = firstName;
    this.mLastName = lastName;
}

public String getmFirstName() {
    return mFirstName;
}

public String getmLastName() {
    return mLastName;
}
}

I then create an the list of Author instances in the MainActivity:

 ArrayList<Author> authors = new ArrayList<>();

    authors.add(new Author("Hans", "Schwabe"));

And use this list when creating the book instance

Book buch = new Book("Säulen der Erde",authors);

When I then try to access the name of the first Author in the list I use the following code:

List<Author> authorArrayList = new ArrayList<Author>();
authorArrayList = buch.getmAuthors();
authorArrayList.get(1).getmFirstName();

And at this point my app keeps crashing.

**

Hence: What would be the right way to retrieve the first name of the first author from the list?

**

Upvotes: 0

Views: 33

Answers (1)

Djaf
Djaf

Reputation: 256

Issue is that you have 1 author and you are trying to retrieve it from index 1. Index should be 0. Indexing in programming is starting from 0.

If you write

authorArrayList.get(0).getmFirstName();

It should work

Upvotes: 1

Related Questions