Delete all elements in array java

How to remove all elements in String array in java? [duplicate]

Remove from what? Do you just want to remove from the example[] array? Or do you have another array where you want to remove the elements present in example array?

6 Answers 6

If example is not final then a simple reassignment would work:

example = new String[example.length]; 

This assumes you need the array to remain the same size. If that’s not necessary then create an empty array:

If it is final then you could null out all the elements:

First approach(reassignment) should only be preferred if it has to be done once or twice or few times. Otherwise every time you will end up allocating memory for new arrays. Also Second approach can not be used for primitive arrays.

example = new String[example.length]; 

If you need dynamic collection, you should consider using one of java.util.Collection implementations that fits your problem. E.g. java.util.List.

Reassign again. Like example = new String[(size)]

list.clear() is documented for clearing the ArrayList.

list.removeAll() has no documentation at all in Eclipse.

Usually someone uses collections if something frequently changes.

 List someList = new ArrayList(); // initialize list someList.add("Mango"); someList.add(". "); // remove all elements someList.clear(); // empty list 

An ArrayList for example uses a backing Array . The resizing and this stuff is handled automatically. In most cases this is the appropriate way.

Источник

Remove all elements from array in Java

I have a doubt in deleting all elements by number in array of objects in Java , it will not be recommended to use ArrayList, the method works but only that it does not eliminate some elements leaving some elements modified, because of their positions in the array class Pack

public class Pack < static int nextNumber = 0; int number; String name; public Pack(String name) < this.number = ++nextNumber; this.name = name; >@Override public String toString() < return "Pack ID:" + number + " - Name: " + name; >> 
class Container < static int nextNumber = 0; int number; int qtPack; Pack[] packs; public Container() < this.number = ++nextNumber; this.qtPack = 0; this.packs = new Pack[10]; >public boolean addPack(Pack pack) < packs[qtPack] = pack; qtPack++; return true; >public Pack removePack(int numberPack) < int idx; Pack removePack = null; idx = indexOfPackByID(numberPack); if (idx != -1) < removePack = packs[idx]; if (removePack != null) < for (int i = idx; i < qtPack - 1; i++) < packs[i] = packs[i + 1]; >qtPack--; > > return removePack; > private int indexOfPackByID(int numberPack) < for (int i = 0; i < qtPack; i++) < if ((packs[i] != null) && (packs[i].number == numberPack)) < return i; >> return -1; > > 
public class Main < public static void main(String[] args) < Pack[] packs = new Pack[5]; packs[0] = new Pack("A"); packs[1] = new Pack("B"); packs[2] = new Pack("C"); packs[3] = new Pack("D"); packs[4] = new Pack("E"); Container container = new Container(); for (int i = 0; i < packs.length; i++) < container.addPack(packs[i]); >System.out.println("--- PACK IN CONTAINER ---"); for (int i = 0; i < container.qtPack; i++) < System.out.println(container.packs[i].toString()); >System.out.println("\n--- REMOVE PACK ---"); for (int i = 0; i < container.qtPack; i++) < Pack pack = container.removePack(container.packs[i].number); System.out.println("Remove " + pack.name+" - ID: "+pack.number); >> > 
--- PACK IN CONTAINER --- Pack ID:1 - Name: A Pack ID:2 - Name: B Pack ID:3 - Name: C Pack ID:4 - Name: D Pack ID:5 - Name: E --- REMOVE PACK --- Remove A - ID: 1 Remove C - ID: 3 Remove E - ID: 5 

Источник

How to Remove Array Elements in Java

How to Remove Array Elements in Java

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

When we create an array in Java, we specify its data type and size. This is used by JVM to allocates the necessary memory for array elements. There are no specific methods to remove elements from the array.

1. Removing an element from Array using for loop

This method requires the creation of a new array. We can use for loop to populate the new array without the element we want to remove.

package com.journaldev.java; import java.util.Arrays; public class Main  public static void main(String[] args)  int[] arr = new int[]1,2,3,4,5>; int[] arr_new = new int[arr.length-1]; int j=3; for(int i=0, k=0;iarr.length;i++) if(i!=j) arr_new[k]=arr[i]; k++; > > System.out.println("Before deletion :" + Arrays.toString(arr)); System.out.println("After deletion :" + Arrays.toString(arr_new)); > > 

Arr Delete

The code removes the element at index 3. This method simply copies all the elements except the one at index 3 to a new array.

2. Deleting an array element by its value

Unlike the previous case, this code will delete the element based on its value. This will not work with duplicates since the size of the array after deletion has to be known.

package com.journaldev.java; import java.util.Arrays; public class Main  public static void main(String[] args)  int[] arr = new int[]1,2,3,4,5>; int[] arr_new = new int[arr.length-1]; int j=3; for(int i=0, k=0;iarr.length;i++) if(arr[i]!=j) arr_new[k]=arr[i]; k++; > > System.out.println("Before deletion :" + Arrays.toString(arr)); System.out.println("After deletion :" + Arrays.toString(arr_new)); > > 

Arr Delete based on value

The only difference between this and the previous case is arr[i]!=j in the if condition in place of i!=j .

3. Deleting element by its value when the array contains duplicates

Performing deletion based on the value in case of duplicates requires using ArrayList. Since ArrayList doesn’t require the size to be now in advance, it allows us to expand dynamically.

package com.journaldev.java; import java.util.ArrayList; import java.util.Arrays; public class Main  public static void main(String[] args)  int[] arr = new int[]1,3,3,4,5>; ArrayListInteger> arr_new = new ArrayList>(); int j=3; for(int i=0;iarr.length;i++) if(arr[i]!=j) arr_new.add(arr[i]); > > System.out.println("Before deletion :" + Arrays.toString(arr)); System.out.println("After deletion :" +arr_new); > > 

array-deletion-duplicates

4. Shifting elements in the same array

This method involves shifting the elements in the same array. Shifting of elements replaces the element to be deleted by the element at the next index.

package com.journaldev.java; import java.util.Arrays; public class Main  public static void main(String[] args)  int[] arr = new int[]1,3,3,4,5>; int j=3; System.out.println("Before deletion :" + Arrays.toString(arr)); int count =0; for(int i = 0; i  arr.length; i++) if(arr[i] == j) count++; // shifting elements for(int k = i; k  arr.length - 1; k++) arr[k] = arr[k+1]; > i--; // break; > > System.out.print("After Deletion :" ); for(int i = 0; i  arr.length-count; i++) System.out.print(" " + arr[i]); > System.out.println(); System.out.println("Whole array :" + Arrays.toString(arr)); > > 

Shifting Elements In Array

Count variable indicates the number of elements deleted. This variable is essential to keep a track of index till which the array should be printed. This method takes care of duplicates as well.

5. Deleting elements from ArrayList

ArrayList is backed by arrays. The deletion of an element in the ArrayList is straight forward. It requires one simple call to an inbuilt function.

package com.journaldev.java; import java.util.ArrayList; import java.util.Arrays; public class Main  public static void main(String[] args)  int[] arr = new int[]1,3,3,4,5>; ArrayListInteger> arr_new = new ArrayListInteger>(); for (int i : arr)  arr_new.add(i); > arr_new.remove(3); System.out.println("Before deletion :" + Arrays.toString(arr)); System.out.println("After Deletion:" + arr_new); > > 

ArrayList Deletion

A call to the remove(i) function removes the element at index i. Deletion in ArrayLists is relatively easier as compared to Arrays.

Conclusion

We saw some examples of deleting elements in an array using different methods. The difference between the deletion of an element in an Array and an ArrayList is clearly evident. If deletion is to be performed again and again then ArrayList should be used to benefit from its inbuilt functions. Same is the case with the addition of elements to an array. ArrayList due to its dynamic nature provides easier and less cumbersome ways to alter an array.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

How to remove everything from an ArrayList in Java but the first element

So I want to remove everything but the first item, so why doesn’t this work? As I get it, after removal, array keys are rearranged or not?

As far as i can understand, you’re picking the size of a list named itemizedOverlay, and you work on another list named mapOverlays. I hope that’s normal 😉

11 Answers 11

mapOverlays.subList(1, mapOverlays.size()).clear(); 

+1 It is just unbelievable to me that this is not the highest-rated answer. It’s both the simplest to code and likely to be the most efficient (as each List implementation will perform the task in the most optimal way given its structure).

This is a useful way of writing it. If you actually look at the code, though, it uses the protected removeRange , and does essentially the exact same thing as Plamena’s solution. The main difference is the number of method calls, and where the loop is. With a good JIT, I suspect they have fairly similar performance. Clearly, the big O is the same.

@Matthew: It depends on the List implementation. For ArrayList (in the OpenJDK sources, at least), removeRange calls System.arraycopy once and makes no other method calls. In this particular case, it moves 0 elements, so essentially all it does is set the array elements to null in a tight loop and update the size field.

As I get it, after removal, array keys are rearranged or not? Yes, the item which was on position 2 is on position 1 after you removed the item on position 1.

Object obj = mapOverlays.get(0); // remember first item mapOverlays.clear(); // clear complete list mapOverlays.add(obj); // add first item 

This may work but it causes the list to enter an unnecessary intermediate state. If the list is used concurrently (perhaps it’s a CopyOnWriteArrayList), you should avoid this solution.

Why don’t you try backwards?

int size = itemizedOverlay.size(); for(int n=size-1;n>0;n--)

-1 On some List implementations this will perform terribly, and it will never be anywhere near optimal.

@Kevin, the OP isn’t using «some List.» He said in no uncertain terms it’s an ArrayList . As far as I know, this will be O(n) for all lists built into Java. This includes LinkedList .

I think it would be faster to create a new ArrayList with just the first element inside. something like :

E temp = mapOverlays.get(0); mapOverlays = new ArrayList().add(temp); 

Btw, Daniel’s proposal is maybe better, because it doesn’t create a new object. So references to the object stay.

add returns a boolean , so you can’t do mapOverlays = new ArrayList().add(temp); You need two statements, mapOverlays = new ArrayList(); and mapOverlays.add(temp);

An ArrayList has integer indices from 0 to size() — 1 . You could do:

int size = mapOverlays.size(); for(int n=1;n

This probably matches what you expect from PHP. It works by continually removing the 1th element, which changes. However, this has poor performance, since the internal array must constantly be shifted down. It is better to use clear() or go in reverse order.

It’s too bad removeRange is protected, as that would be convenient for this type of operation.

+1 for pointing out the performance disadvantage of your potential solution. Also. remember you can always extend ArrayList and make public any methods which were protected.

You don’t need removeRange (and the issue is not that it’s protected, but that it doesn’t even exist on the List interface (and rightly so)). See Adam Crune’s answer.

@Kevin, the OP isn’t using the List interface, so that’s a non-sequitur. You could argue he should, but maybe he is sure he explicitly wants an array-based class for its performance characteristics.

mapOverlays = Collections.singletonList(mapOverlays.get(0)); 

Maybe not what the OP wants — the resulting list has nothing but the first element but you can’t add anything to it anymore. So it’s not a wrong answer but it introduces some limitations.

If you are using a java.util.List implementation instead of array, the size of the array gets smaller everytime you remove something and the n+1 item replaces the n item. This code will eventually result to ArrayIndecOutOfBoundsException when n becomes greated than the last index in the list.

Java also has an array type and the size of that one cannot be changed:

Object[] mapOverlay = //initialize the array here int size = mapOverlay.length; for(int n=1;n

I don’t know PHP but this sounds like it’s close to the behavior you are after. However the List implementations are more flexible and comfortable in use than the arrays.

Источник

Читайте также:  Зачем нужен index php
Оцените статью