In java, to remove an element in an array, can you set it to null?

I'm trying to make a delete method that works on implementing a list array. Can I set a duplicate of an element to null to remove it? Assuming the list is ok.

ArrayList a = new ArrayList[]; public void removeduplicates(){ for(a[i].equals(a[i+1]){ a[i+1] = null; } a[i+1] = a[i]; } 
-1
source share
9 answers

No, you cannot remove an element from an array, as when reducing it. Java arrays have a fixed size. For this you need to use an ArrayList .

If you set the element to null, the array will still be the same size, but with a null reference at that point.

  // Let say a = [0,1,2,3,4] (Integer[]) a[2] = null; // Now a = [0,1,null,3,4] 
+3
source

Yes, you can set the elements in the array to zero, but code like a[i].equals(a[i+1]) will fail with a NullPointerException if the array contains zeros, so you need to be more careful if you know that your array may contain zeros. It also does not resize the array, so you will waste memory if you delete a large number of elements. Fixed-size arrays are usually not a good way to store data if you often add and remove elements - as you can guess by their name.

+2
source

Is it possible to set a duplicate of an element to null to remove it?

You can set the array element to null , but that will not delete the array element ... it just set the element to null (I feel like I am repeating the first sentence).

Instead, you should return a cleared copy of the array. One way to do this is to use the java.util.Set broker:

 String[] data = {"A", "C", "B", "D", "A", "B", "E", "D", "B", "C"}; // Convert to a list to create a Set object List<String> list = Arrays.asList(data); Set<String> set = new HashSet<String>(list); // Create an array to convert the Set back to array. String[] result = new String[set.size()]; set.toArray(result); 

Or just use java.util.Set :)

+2
source

The direct answer to your question is that setting the array or ArrayList element to null gives you a null entry in the array or ArrayList. This is not the same as deleting an item. If it simply means that a[i] or a.get(i) will return null , not the original element.

The code in the question is garbled. If you are going to use an ArrayList, a simplified solution would look something like this:

 ArrayList a = new ArrayList(); public void removeduplicates() { for (int i = 0; i < a.size() - 1; ) { if (a.get(i).equals(a.get(i + 1)) { a.remove(i); } else { i++; } } } 

but in the worst case it is O(N**2) , because every call to remove copies all elements with indices greater than the current value of i .

If you want to improve performance, do the following:

 public ArrayList removeduplicates() { ArrayList res = new ArrayList(a.size()); if (a.size() == 0) { return res; } res.add(a.get(0)); for (int i = 1; i < a.size(); i++) { if (!a.get(i - 1).equals(a.get(i)) { res.add(a.get(i)); } } return res; } 

(This is a quick hack. I'm sure it could be removed.)

+2
source

Is this a home issue?

Your problem is similar to the uniq thread-processing program: Save - by copying - any element that doesn't match the one in front of it. It only removes all duplicates if the sequence is sorted. Otherwise, only adjacent duplicates are deleted. This means that you need to buffer no more than one element (even if by reference) to use as a comparison predicate when deciding whether to save the element that follows in the sequence.

The only special case is the first element. Since it should never match the previous element, you can try to initialize your buffer "previous" element to a value that is from a domain of the sequence type, or you can use iteration with the flag "first element" in a special case or explicitly copy the first element outside iterations - given the case when the sequence is also empty.

Please note that I did not offer you to perform this operation as a destructive algorithm in place. This would be appropriate with a structure like a linked list with constant overhead to delete an item. As others have noted, removing an element from an array or vector involves dragging successor elements to β€œfill in the hole,” which has a time complexity of n among the successors.

+2
source

The example of your code was rather confusing. With ArrayList[] you showed an array of ArrayList objects.

Assuming you're only talking about java.util.ArrayList , then the easiest way to get rid of duplicates is to use java.util.Set instead, as others have mentioned. If you really want to start or end with List for some reason, follow these steps:

 List withDuplicates = new ArrayList() {{ add("foo"); add("bar"); add("waa"); add("foo"); add("bar"); }}; // Would rather have used Arrays#asList() here, but OK. List withoutDuplicates = new ArrayList(new LinkedHashSet(withDuplicates)); System.out.println(withoutDuplicates); // [foo, bar, waa] 

This is where LinkedHashSet is selected because it maintains order. If you're not worried about ordering, HashSet is faster. But if you really want it to be sorted, the TreeSet value might be more valuable.

On the other hand, if you are talking about a real array , and you want to filter duplicates from this without the help of (excellent) Collection structure , then you will need to create another array and add elements one by one to it while you check if the array is 't already contains the item to be added. Here is a basic example (without the help of Arrays.sort() and Arrays.binarySearch() , which would make the task easier, but then you get a sorted array):

 String[] array1 = new String[] {"foo", "bar", "foo", "waa", "bar"}; String[] array2 = new String[0]; loop:for (String array1item : array1) { for (String array2item : array2) { if (array1item.equals(array2item)) { continue loop; } } int length = array2.length; String[] temp = new String[length + 1]; System.arraycopy(array2, 0, temp, 0, length); array2 = temp; array2[length] = array1item; } System.out.println(Arrays.toString(array2)); // [foo, bar, waa] 

Hope this gives new ideas.

+2
source

If you implement your own list, and you decide to use the storage mechanism of the basic primitives. Thus, using an array (rather than an arraylist) may be where you start.

For easy implementation, your strategy should consider the following.

Decide how to expand your list. You can create copies of data blocks of 200 cells at a time. You would use only 199 because you could use the last cell to store the next block of allocation.

Such a linked list is terrible, so you can use a master block to store all instances of blocks. You create a master block of size 100. You start with one data block 200 and store its ref in master [0]. As the size of the list grows, you gradually save the ref of each new data block to master [1] .... master [99], and then you may have to recreate the main list to store 200 links.

For efficiency reasons, when you delete a cell, you should not actually destroy it immediately. You let it hang until enough deletion occurs so you can recreate the block.

You need to note somehow that the cell has been deleted. So the answer is obvious, of course, you can set it to zero, because you are the king, emperor, dictator who decides how the cell is marked as deleted. Using null is a great and common way. If you use null, you need to prevent null values ​​from being entered as data in your list class. You would have to make an exception if such an attempt is made.

You need to develop and write a garbage collection procedure and strategy to combine the list, recreating blocks to remove invalid cells in the mass. The JVM does not know that this is "deleted" data.

You need a register to count the number of deletions, and if this threshold is crossed, garbage collection will be collected. Or you ask the programmer to call the compact () method. Because if deletions are sparse and distributed between different data blocks, it is also possible to delete null / deleted cells. You can only combine adjacent blocks and only if the sum of the holes in both blocks is up to 200. Obviously,

Perhaps when data is added to the list, you intentionally leave zero spaces between the data. It’s like driving along the street, and you see that the addresses of the houses increase by ten, because the city decided that if people want to build new houses between existing houses. This way you do not need to recreate and break the block every time an insert occurs.

Therefore, the answer is obvious to you, of course, you can write null to indicate that the cell has been deleted, because this is your list class management strategy.

+2
source

No, an array element containing null still exists, it just does not contain a useful value.

You can try to move each element from the further down to the list up by 1 element to fill in the gap, then you have a space at the end of the array - the array will not hide from this!

If you do this a lot, you can use System.arraycopy() for a quick packaging operation.

+1
source

Use ArrayList.remove (index int).

  if(a[i].equals(foo())) a.remove(i) 

But be careful when using for-loops and deleting objects in arrays.

http://java.sun.com/j2se/1.3/docs/api/java/util/ArrayList.html

+1
source

Source: https://habr.com/ru/post/1308952/


All Articles