简体   繁体   中英

In Java how can I add an object to an array via the object's constructor?

I'm a fairly novice Java developer. I have a Book class to represent a book, and a Library class to represent a library.

Some code from the Library class:

/**
 * method to populate books list
 */
public static void populateBooksList() {

    // instantiate books

    Book b1 = new Book("Catch 22", "Heller", "Thriller", 5, 1, false);
    Book b2 = new Book("The Hobbit", "Tolkien", "Fantasy", 4, 2, false);
    Book b3 = new Book("Gullivers Travels", "Swift", "Adventure", 3, 3,
            false);
    Book b4 = new Book("Moby Dick", "Melville", "Crime", 4, 4, false);
    Book b5 = new Book("The Lord of the Rings", "Tolkien", "Fantasy", 4, 5,
            false);

    // populate the array

    books[0] = b1;
    books[1] = b2;
    books[2] = b3;
    books[3] = b4;
    books[4] = b5;

}

And some code from the Book class (I didn't paste all the gets / sets in):

public class Book {

    /**
     * declaring var for genre
     */
    private String genre;

    /**
     * declaring var for rating
     */
    private int rating;

    /**
     * declaring var for name
     */
    private String name;

    /**
     * declaring var for ID
     */
    private int iD;

    /**
     * declaring var for author
     */
    private String author;

    /**
     * declaring var for onLoan
     */
    private Boolean onLoan;

    /**
     * default constructor
     */
    public Book() {

    }

    /**
     * constructor with args
     * 
     * @param nameP
     *            - book name
     * @param authorP
     *            - book author
     * @param genreP
     *            - book genre
     * @param ratingP
     *            - book rating
     * @param iDP
     *            - book ID
     * @param onLoanP
     *            - onLoan
     */
    public Book(String nameP, String authorP, String genreP, int ratingP,
            int iDP, Boolean onLoanP) {
        this.name = nameP;
        this.iD = iDP;
        this.author = authorP;
        this.onLoan = onLoanP;
        this.genre = genreP;
        this.rating = ratingP;
    }

What I want to do is make adding the books to the array more efficient. If I have 50 books, I'll need 50 lines of code just to populate the array. I'd like to use the constructor in the Book class, or the gets / sets in the Book class somehow, or some other way using code contained in the Book class in order to automatically add each object to the array as it is instantiated. Is this possible?

Thanks

S.

You are asking more about general concepts of programming, not Java itself.

In short - constructor's sole responsibility is to create and initialize an object. Doing anything else in a constructor would be a bad practice.

You can use a factory pattern though:

public class BookCollection {
    public static final int MAX_COUNT = 20;

    private int count = 0;
    private Book[] books = new Book[MAX_COUNT];

    public Book createBook(String nameP, String authorP, String genreP, int ratingP, int iDP, Boolean onLoanP) {
        books[count] = new Book(nameP, authorP, genreP, ratingP, iDP, onLoanP);

        return books[count++];
    }

    public Book[] getBooks() {
         return books;
    }
}

This implementation is open for many problems - like too many books created, concurrent access issues and many others.

But should give you a guidance, where to go.

Personally I would rather go with a collection, such as ArrayList. Not an array. Arrays are great in some cases, but most of the time an ArrayList will be much better.

public class BookCollection {
    private List<Book> books = new ArrayList<Book>();

    public Book createBook(String nameP, String authorP, String genreP, int ratingP, int iDP, Boolean onLoanP) {
        Book result = new Book(nameP, authorP, genreP, ratingP, iDP, onLoanP)

        books.add(result);

        return result;
    }

    public List<Books> getBooks() {
         return Collections.unmodifiableList(books);
    }
}

You can assign the book directly to the array index:

books[0] = new Book("Catch 22", "Heller", "Thriller", 5, 1, false);
books[1] = new Book("The Hobbit", "Tolkien", "Fantasy", 4, 2, false);
books[2] = new Book("Gullivers Travels", "Swift", "Adventure", 3, 3, false);
books[3] = new Book("Moby Dick", "Melville", "Crime", 4, 4, false);
books[4] = new Book("The Lord of the Rings", "Tolkien", "Fantasy", 4, 5, false);

EDIT to answer comment:

In this case you are assigning the book directly to the array position without using another variable. If you now did Book b1 = books[0]; you would be still be able to get a reference to the book at index 0.

In hindsight though the other answers that recommended using an array initializer are better and do the same thing. This way you don't even need to specify the size of your array or the index upfront:

Book[] books = new Book[] {
    new Book("Catch 22", "Heller", "Thriller", 5, 1, false);
    new Book("The Hobbit", "Tolkien", "Fantasy", 4, 2, false);
    new Book("Gullivers Travels", "Swift", "Adventure", 3, 3, false);
    new Book("Moby Dick", "Melville", "Crime", 4, 4, false);
    new Book("The Lord of the Rings", "Tolkien", "Fantasy", 4, 5, false);
}

If you use primitive arrays (ie, Books[]) instead of data structures like List/Vector, I think you can use normal array init. eg,:

Book[] books = {new Book(bla,bla,bla), new Book(foo,foo,foo),... };

However, I tend to prefer data structures, and there are ways to initialize those with constants, depending on the structure and the library.

Caveat: I recognize that the entire approach here is problematic, I'm just answering the question as asked.

Stick everything in an arraylist, let it manage its own size and then dump the contents into an array sized off the arraylist.

public Book(String title, String author, String genre, int rating, 
            int id, boolean onLoad, ArrayList<Book> array)
{
    //initialize stuff
    array.add(this);
}

In the main code where you're setting up the objects:

ArrayList<Book> tmpArray = new ArrayList<>();
//build your Book objects, passing in tmpArray
Book array[] = tmpArray.toArray(new Book[tmpArray.size()]);

And you have the array that you desired.

// Poor
private Book[] books = new Book[5];
...
Book b1 = new Book("Catch 22", "Heller", "Thriller", 5, 1, false);
Book b2 = new Book("The Hobbit", "Tolkien", "Fantasy", 4, 2, false);
...
books[0] = b1;
books[1] = b2;

// Better
Book[] books = new Book[] {
  new Book("Catch 22", "Heller", "Thriller", 5, 1, false),
  new Book("The Hobbit", "Tolkien", "Fantasy", 4, 2, false)
};
...

// Better still
private ArrayList<Book> books = new ArrayList<Book>();
books.add(new Book("Catch 22", "Heller", "Thriller", 5, 1, false);
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM