Reputation: 19
Write a statement that will remove the first element of the ArrayList names and store it in String firstName.
So this problem seems very simple and straight forward, this is answer I came up with:
String firstName = names[0];
names.remove(0);
But my teacher said it was wrong and that the answer is:
firstName = names.remove(0);
I agree that the second code is correct, but I am still convinced that my code is also correct. Can someone explain to me why it is wrong?
Upvotes: 1
Views: 1167
Reputation: 13640
If you are talking about the logic, you are right! Storing the first element in a string and then removing it from the list shouldn't be a problem. But I think your teacher wants you to learn more about java
, here.. emphasizing that remove
function of ArrayList
returns the element removed. etc..
If you are talking about syntax, previous answers say it!
HTH!
Upvotes: 0
Reputation: 7824
You cannot access an element of an ArrayList
by using list[0]
-- that syntax is for Arrays. The major difference between an Array and an ArrayList
is difference is that an Array is a fixed length data structure while ArrayList
is a variable length Collection class.
You can use something like these examples:
Get the first element in the list.
String s1 = list.get(0);
Get the first element in the list and remove it from the list.
String s2 = list.remove(0);
Upvotes: 1
Reputation: 3755
If you are using java or android (according to your name), then you cannot access arrayList Items like this:
names[0];
it should be something like this:
names.get(0);
Upvotes: 0