简体   繁体   中英

Java - Cannot remember how to remove an item from a list

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

I cannot remember how to remove the item from the list, please help.

This was my solution, thank everyone very much!

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

Array is a fixed size datastructure. You cannot reduce the size of it. You can however, overwrite contents and maintain a counter which tells you the effective size. Basically, you shift the entries to the left by one slot.

In your example, you can do something like this:

Let us assume that you want to remove a[5] and there are 10 elements in the array.

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

With this, your array would now look like

Before this code:

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

After this code:

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

We have overwritten the "don" entry here. And we now have to maintain a new counter which is now going to be the length of the array and this is going to be one less than array.length. And you would be using this new variable for processing the array.

In the program you are using string array. If you want to remove element from list then you can remove element in this way :

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

If you want remove all elemnt from list then you can use this line :

list.removeAll(//Your list);

You can do in this way :

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

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