简体   繁体   English

将ArrayList元素存储在字符串中

[英]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. 编写一条语句,该语句将删除ArrayList名称的第一个元素并将其存储在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 . 您不能使用list[0]访问ArrayList的元素-该语法适用于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. ArrayArrayList之间的主要区别在于, Array是固定长度的数据结构,而ArrayList是可变长度的Collection类。

ArrayList Documentation . ArrayList文档


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: 如果您使用的是Java或android(根据您的名字),则无法访问arrayList项目,如下所示:

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. 但是我认为您的老师希望您在这里了解更多有关java 。.强调ArrayList remove函数返回被删除的元素。 etc.. 等等..

If you are talking about syntax, previous answers say it! 如果您在谈论语法,那么以前的答案就可以说!

HTH! HTH!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM