gpt4 book ai didi

java - 如何从数组列表中删除元素?

转载 作者:行者123 更新时间:2023-12-02 02:51:33 24 4
gpt4 key购买 nike

所以我想询问用户是否想从数组列表中删除一个元素。数组列表是从文件中读入的最喜欢的颜色的列表。假设数组列表的内容是 - 红、橙、绿、蓝。我想知道如何根据用户输入删除元素。会不会是这样的 -

System.in.println("Which color would you like to remove")
removeColor = reader.nextString
if removeColor (//using pseudo code here) contains removeColor, remove from ArrayList

我走在正确的道路上吗?到目前为止,这是我的代码。谢谢!

Scanner input = new Scanner(System.in);
ArrayList <String> favoriteColors = new ArrayList <String>();
boolean repeat = true;
while (repeat) {

System.out.println("Enter the name of the file which contains your favorite colors ");
String fileName = input.nextLine().trim();

try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {

String line;
System.out.println("Here are your favorite colors according to the file:");
while ((line = reader.readLine()) != null) {
System.out.println(line);
favoriteColors.add((line));
}

System.out.println("Add more? (y/n)");
if (input.next().startsWith("y")) {
System.out.println("Enter : ");
favoriteColors.add(input.next());
} else {
System.out.println("have a nice day");
}
for (int i = 0; i < favoriteColors.size(); i++) {
System.out.println(favoriteColors
if (input.next().startsWith("y")) {
System.out.println("Remove a color?")
if (input.next().startsWith("y")) {
/something along the lines of the pseudo code I wrote above

最佳答案

您需要了解 ArrayList 中的删除方法如何工作:

remove方法的实现如下:

public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}

than 表示列表中包含的对象必须能够实现此条件:

if (o.equals(elementData[index])) {

因此:

如果您的favoriteColors类只是字符串,那么它就可以工作

但是如果它们是您定制的,那么您需要在该类中实现 equals。

关于java - 如何从数组列表中删除元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43774257/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com