Java - 不记得如何从列表中删除项目


private String[] names = { "bobby", "jones", "james", "george", "cletus", "don", "joey" };
public String getName() {
    Random random = new Random();
    String name = "";
    int num = random.nextInt(names.length-1);
    name = names[num];
    names[num] = null; //HOW TO REMOVE FROM THE LIST???
    return name;
}

我不记得如何从列表中删除该项目,请帮忙。

这是我的解决方案,非常感谢大家!

private String[] names = { "bobby", "jones", "james", "george", "cletus", "don", "joey" };
ArrayList<String> list = new ArrayList<String>(Arrays.asList(names));
public String getName() {
    Random random = new Random();
    String name = "";
    int num = random.nextInt(names.length - 1);
    name = list.get(num);
    list.remove(num);
    return name;
}
数组

是一个固定大小的数据结构。您无法减小它的大小。但是,您可以覆盖内容并维护一个告诉您有效大小的计数器。基本上,您将条目向左移动一个插槽。

在您的示例中,您可以执行以下操作:

让我们假设您要删除 a[5],并且数组中有 10 个元素。

for( int inx = 5; inx < 9; inx++ )
{
    array[inx] = array[inx+1]
}
int arrayLength = array.length; // Because you are overwriting one entry.

有了这个,您的数组现在看起来像

在此代码之前:

"bobby", "jones", "james", "george", "cletus", "don", "joey", "pavan", "kumar", "luke"

在此代码之后:

"bobby", "jones", "james", "george", "cletus", "joey", "pavan", "kumar", "luke", "luke"

我们在这里覆盖了"don"条目。我们现在必须维护一个新的计数器,它现在将是数组的长度,这将比 array.length 少一个。您将使用这个新变量来处理数组。

在程序中,您正在使用字符串数组。如果要从列表中删除元素,则可以通过以下方式删除元素:

for (Iterator<String> iter = list.listIterator(); iter.hasNext(); ) {
  String a = iter.next();
  if (//remove condition) {
     iter.remove();
  }
}

如果要从列表中删除所有参数,则可以使用此行:

list.removeAll(//Your list);

你可以这样做:

String[] names = { "bobby", "jones", "james", "george", "cletus", "don", "joey" };
List<String> list = new ArrayList<String>(Arrays.asList(names));
Random random = new Random();   
int num = random.nextInt(names.length-1);    
list.remove(num);    
System.out.println(Arrays.asList(list.toArray(new String[list.size()])));  //Print the value of updated list

最新更新