I've made an ArrayList called books, which only contains the class LibraryBook that I've created. And I've created this in another class called Library.
public class Library {
ArrayList<LibraryBook> books;
public Library() {
books = new ArrayList<LibraryBook>();
}
Then I have a method in this Library class which adds LibraryBooks to this ArrayList.
public void add( String title, String author) {
LibraryBook b = new LibraryBook( title, author);
books.add( b);
}
So if I say, in a main method;
Library library = new Library();
library.add( "Title", "Author");
I get a new LibraryBook in my ArrayList. However if I do this again;
Library library = new Library();
library.add( "anotherTitle", "anotherAuthor");
Now I have another LibraryBook in my ArrayList. But in the add method, I've made LibraryBook b to refer to these objects. So what refers to these objects now? Are they both referred by the variable b (which shouldn't happen as far as Java is concerned)? Or they don't have any references at all?
My guessing would be, that when I put an object into an ArrayList, it creates a referrence to this object and stores that instead. And if I put a reference to an object into an ArrayList, it does the same thing.
If this is true, then another question, how does Java let me create two different LibraryBooks that are referred with the same variable b in my add method?
EDIT: I've found another thread with the same title before I made this post, but I didn't quite get the answer I was looking for so here we go.
EDIT2: With all due respect, how is this question any relevant to the linked post? The linked post is so "general" that any post in this forum can be linked to that one and considered as a duplicate. It doesn't hold an answer to my question at all. Even the word ArrayList is not present in there. I would appreciate a feedback on how the two posts are even related other than the fact that the linked post is a general "lesson" for the basics of Java.