0

I have declared an ArrayList to store my objects of the class Books.

static ArrayList<Books> bookData = new ArrayList<Books>();

So I have multiple methods inside class Books. Let's say I have a method named... getName(), Let's assume I have objects stored inside ArrayList and I want to call the method for the object stored in the array list.

So Is this correct:

bookData[1].getName();

or

Is this correct:

bookData.get(1).getName();

If the first is wrong, then why? Is there a method to call the object stored inside ArrayList?

4
  • what errors do you get? Commented Oct 3, 2018 at 17:37
  • The first one is the syntax for an array and the second one is for arraylist. So the first one will not work for the arraylist. Commented Oct 3, 2018 at 17:41
  • An array is a language construct, and its elements can be accessed by using [index] Commented Oct 3, 2018 at 21:22
  • And just so that I could sleep well, can you please change the class name from Books to Book in your code, so that you could have a proper array of objects Book (long shelf). Thank you. (Unless you planned on building a custom bookcase) Commented Oct 3, 2018 at 22:34

2 Answers 2

4
bookData[1].getName();

This is incorrect because the [1] syntax only works for an array. It does not work with an ArrayList.

Sign up to request clarification or add additional context in comments.

1 Comment

OK, Thank you for the clarification.
2

for Arraylist you can use only

bookData.get(1).getName();

bookData[1].getName(); is used only with Array and Not with Arraylist

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.