-2

Given an Array of n Objects, let's say is an Array of Strings, and it has the following values:

foo[0]="a";
foo[1]="cc";
foo[2]="a";
foo[3]="dd";

What do I have to do to remove a certain String/Object? Thanks!

Que
  • 11
  • 5

1 Answers1

1

in an array you can't remove objects in the way you mean (you can replace them with null but I don't think that's what you mean. An array is a series of boxes, you can put anything in each box, but you can't pull one box out and tape the rest back together

An ArrayList on the other hand has .add and .remove methods that would allow you to remove a certain object from it.

See this example of how arrayList works

   public static void main(String args[]) {
        ArrayList<String> list=new ArrayList<String>();
        list.add("zero");
        list.add("one");
        list.add("two");
        list.add("three");
        list.add("four");

        list.remove(2); //remove by index 
        list.remove("three");

        for(int i=0;i<list.size();i++){
            System.out.println(list.get(i));
        }
   }

If a particular function really needs an array there are methods to convert back to an array

    String[] array=new String[list.size()];

    list.toArray(array); //fills array with contents of list

    for(int i=0;i<array.length;i++){
        System.out.println(array[i]);
    }
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Richard Tingle
  • 16,906
  • 5
  • 52
  • 77