简体   繁体   中英

Storing ArrayList Elements in a String

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?

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

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

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!

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