20

I have an array like this:

String n[] = {"google","microsoft","apple"};

What I want to do is to remove "apple".

My problem is very basic,however,I searched the website and I found out that java doesn't really support the deleting feature from an array.I also heard to use Java Utils, because it's so simple to remove an item....I tried to find Java Utils on google, but almost all links are dead.

So finally...is there any way to remove a string from an array of string?

Even if I use an ArrayList I can't find a method to generate a random item in it! For ex: in a normal array I generate a string like this:

String r = myAL[rgenerator.nextInt(myAL.length)];

In an arraylist it doesn't work....maybe you know a solution...

2
  • You were probably referred to the package java.util, which contains some of the classes folks below are using to answer your question, such as List and ArrayList, and which comes with the standard Java library - no need for a separate download. Commented Oct 29, 2011 at 17:16
  • 7
    NO!! You want to remove Microsoft. Commented Oct 29, 2011 at 18:35

5 Answers 5

28

Define "remove".

Arrays are fixed length and can not be resized once created. You can set an element to null to remove an object reference;

for (int i = 0; i < myStringArray.length(); i++)
{
    if (myStringArray[i].equals(stringToRemove))
    {
        myStringArray[i] = null;
        break;
    }
}

or

myStringArray[indexOfStringToRemove] = null;

If you want a dynamically sized array where the object is actually removed and the list (array) size is adjusted accordingly, use an ArrayList<String>

myArrayList.remove(stringToRemove); 

or

myArrayList.remove(indexOfStringToRemove);

Edit in response to OP's edit to his question and comment below

String r = myArrayList.get(rgenerator.nextInt(myArrayList.size()));
Sign up to request clarification or add additional context in comments.

3 Comments

it's ok but I also need to generate a random item from that list.... In a normal array it's easily done,however in an arraylist it's pretty hard to...If you know how please tell me...
Why would it be "hard to do"? An ArrayList gives you the same random access as an array (via the index). See my edit above.
I recommend using (myStringArray[i].equalsIgnoreCase(stringToRemove)). This will ensure that no matter the type of input from the user, casing does not prevent the string from being removed from the array.
9

It is not possible in on step or you need to keep the reference to the array. If you can change the reference this can help:

      String[] n = new String[]{"google","microsoft","apple"};
      final List<String> list =  new ArrayList<String>();
      Collections.addAll(list, n); 
      list.remove("apple");
      n = list.toArray(new String[list.size()]);

I not recommend the following but if you worry about performance:

      String[] n = new String[]{"google","microsoft","apple"};
      final String[] n2 = new String[2]; 
      System.arraycopy(n, 0, n2, 0, n2.length);
      for (int i = 0, j = 0; i < n.length; i++)
      {
        if (!n[i].equals("apple"))
        {
          n2[j] = n[i];
          j++;
        }      
      }

I not recommend it because the code is a lot more difficult to read and maintain.

1 Comment

Not to mention horribly inefficient; all that copying isn't free. This is why ArrayList was invented.
1

Arrays in Java aren't dynamic, like collection classes. If you want a true collection that supports dynamic addition and deletion, use ArrayList<>. If you still want to live with vanilla arrays, find the index of string, construct a new array with size one less than the original, and use System.arraycopy() to copy the elements before and after. Or write a copy loop with skip by hand, on small arrays the difference will be negligible.

Comments

1

You can't remove anything from an array - they're always fixed length. Once you've created an array of length 3, that array will always have length 3.

You'd be better off with a List<String>, e.g. an ArrayList<String>:

List<String> list = new ArrayList<String>();
list.add("google");
list.add("microsoft");
list.add("apple");
System.out.println(list.size()); // 3

list.remove("apple");
System.out.println(list.size()); // 2

Collections like this are generally much more flexible than working with arrays directly.

EDIT: For removal:

void removeRandomElement(List<?> list, Random random)
{
    int index = random.nextInt(list.size());
    list.remove(index);
}

2 Comments

it's ok but I also need to generate a random item from that list.... In a normal array it's easily done,however in an arraylist it's pretty hard to...If you know how please tell me...
@user1015311: No, you'd do it the same way as for an array - you just remove based on the index instead of the value. There's an overload of remove taking an int. Just create a random number in the range [0, list.size()] then call list.remove(index);.
0
import java.util.*;

class Array {
    public static void main(String args[]) {
        ArrayList al = new ArrayList();
        al.add("google");
        al.add("microsoft");
        al.add("apple");
        System.out.println(al);
        //i only remove the apple//
        al.remove(2);
        System.out.println(al);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.