1

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?

4
  • 1
    are you sure the first code is in valid syntax in java? Commented Feb 13, 2015 at 18:30
  • In what language you are writing?!!! Commented Feb 13, 2015 at 18:30
  • 1
    Did you try to run your example? Or even compile it? My best guess is that you're using Java, in which case, hint: ArrayList != array. Commented Feb 13, 2015 at 18:33
  • 1
    You can not access any element of ArrayList as names[0] in java. It should have been names.get(0) Commented Feb 13, 2015 at 18:38

3 Answers 3

1

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.

ArrayList Documentation.


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);
Sign up to request clarification or add additional context in comments.

1 Comment

@Javasaurus if your question is solved then don't forget to accept one answer so others know it has been solved.
0

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);

Comments

0

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!

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.