Removing an element from an Array (Java) [duplicate]
This question already has an answer here:
How do I remove objects from an array in Java?
19 answers
Is there any fast (and nice looking) way to remove an element from an array in Java?
java arrays element
marked as duplicate by Duncan Jones, Bill the Lizard Nov 27 '13 at 13:18
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
add a comment |
This question already has an answer here:
How do I remove objects from an array in Java?
19 answers
Is there any fast (and nice looking) way to remove an element from an array in Java?
java arrays element
marked as duplicate by Duncan Jones, Bill the Lizard Nov 27 '13 at 13:18
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
4
Even if the question is duplicate, the answer in the other question is neither fast nor nice looking. It transforms the array into an arraylist (by hand).
– f1v3
Sep 22 '17 at 14:37
add a comment |
This question already has an answer here:
How do I remove objects from an array in Java?
19 answers
Is there any fast (and nice looking) way to remove an element from an array in Java?
java arrays element
This question already has an answer here:
How do I remove objects from an array in Java?
19 answers
Is there any fast (and nice looking) way to remove an element from an array in Java?
This question already has an answer here:
How do I remove objects from an array in Java?
19 answers
java arrays element
java arrays element
edited Mar 13 '09 at 14:34
Michael Myers♦
154k37256280
154k37256280
asked Mar 13 '09 at 14:11
Tobias
4,68063764
4,68063764
marked as duplicate by Duncan Jones, Bill the Lizard Nov 27 '13 at 13:18
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
marked as duplicate by Duncan Jones, Bill the Lizard Nov 27 '13 at 13:18
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
4
Even if the question is duplicate, the answer in the other question is neither fast nor nice looking. It transforms the array into an arraylist (by hand).
– f1v3
Sep 22 '17 at 14:37
add a comment |
4
Even if the question is duplicate, the answer in the other question is neither fast nor nice looking. It transforms the array into an arraylist (by hand).
– f1v3
Sep 22 '17 at 14:37
4
4
Even if the question is duplicate, the answer in the other question is neither fast nor nice looking. It transforms the array into an arraylist (by hand).
– f1v3
Sep 22 '17 at 14:37
Even if the question is duplicate, the answer in the other question is neither fast nor nice looking. It transforms the array into an arraylist (by hand).
– f1v3
Sep 22 '17 at 14:37
add a comment |
15 Answers
15
active
oldest
votes
You could use commons lang's ArrayUtils.
array = ArrayUtils.removeElement(array, element)
commons.apache.org library:Javadocs
1
@Clive Guava appears to only work on collections.
– Peter Lawrey
Mar 23 '14 at 7:33
3
does this shrink the array as well?
– Supun Wijerathne
Aug 5 '16 at 8:36
1
@SupunWijerathne it has to, to change the size/length.
– Peter Lawrey
Aug 5 '16 at 9:36
1
It is not working in Java8 and I am not getting any method with the nameremoveElement
– Atul Agrawal
Feb 16 at 8:12
1
ArrayUtils.remove if you want to specify an index, not the value itself
– Line
Dec 10 at 14:43
|
show 2 more comments
Your question isn't very clear. From your own answer, I can tell better what you are trying to do:
public static String removeElements(String input, String deleteMe) {
List result = new LinkedList();
for(String item : input)
if(!deleteMe.equals(item))
result.add(item);
return result.toArray(input);
}
NB: This is untested. Error checking is left as an exercise to the reader (I'd throw IllegalArgumentException if either input or deleteMe is null; an empty list on null list input doesn't make sense. Removing null Strings from the array might make sense, but I'll leave that as an exercise too; currently, it will throw an NPE when it tries to call equals on deleteMe if deleteMe is null.)
Choices I made here:
I used a LinkedList. Iteration should be just as fast, and you avoid any resizes, or allocating too big of a list if you end up deleting lots of elements. You could use an ArrayList, and set the initial size to the length of input. It likely wouldn't make much of a difference.
2
Note, you'll want to useList<String>
result. When I do this in the current compiler, the toArray command gives a type error (the other solution is to cast the result.)
– user1086498
May 27 '13 at 11:28
add a comment |
The best choice would be to use a collection, but if that is out for some reason, use arraycopy
. You can use it to copy from and to the same array at a slightly different offset.
For example:
public void removeElement(Object arr, int removedIdx) {
System.arraycopy(arr, removedIdx + 1, arr, removedIdx, arr.length - 1 - removedIdx);
}
Edit in response to comment (tl;dr):
It's not another good way, it's really the only acceptable way--any tools that allow this functionality (like Java.ArrayList or the apache utils) will use this method under the covers. Also, you REALLY should be using ArrayList (or linked list if you delete from the middle a lot) so this shouldn't even be an issue unless you are doing it as homework.
To allocate a collection (creates a new array), then delete an element (which the collection will do using arraycopy) then call toArray on it (creates a SECOND new array) for every delete brings us to the point where it's not an optimizing issue, it's criminally bad programming.
Suppose you had an array taking up, say, 100mb of ram. Now you want to iterate over it and delete 20 elements.
Give it a try...
I know you ASSUME that it's not going to be that big, or that if you were deleting that many at once you'd code it differently, but I've fixed an awful lot of code where someone made assumptions like that.
2
Following a "deletion" (i.e. shifting the array left by one element) won't there be a duplicate of the end element? i.e. a.length will be the same following the deletion, no? I'm not saying I dislike the idea, just that one needs to be aware of this.
– Adamski
Aug 13 '10 at 12:55
+1. This works for my purposes. (I fixed the small issue you had in your sample. Hope you don't mind.)
– Gunslinger47
Sep 25 '10 at 6:12
Yes, this will just shift the elements left and there will be last element still present. We have to use new array to copy.
– Reddy
Oct 22 '10 at 6:33
BTW, this is what org.apache.commons.lang.ArrayUtils does too.
– Reddy
Oct 22 '10 at 6:34
It's assumed that if you are adding and deleting elements from an array you are also tracking the "Last" item in the array, so copying shouldn't be necessary.
– Bill K
Feb 23 '11 at 20:43
add a comment |
You can't remove an element from the basic Java array. Take a look at various Collections and ArrayList instead.
i know, i just want a beautiful looking way with arraylists or sth. like that, any hint for that?
– Tobias
Mar 13 '09 at 14:15
+1: Use LinkedList, life is simpler.
– S.Lott
Mar 13 '09 at 14:17
7
LinkedList is rarely a good idea. The List intrrface gives you random access, but LinkedList gives O(n) access times instead of O(1).
– Tom Hawtin - tackline
Mar 13 '09 at 14:24
1
You can remove an element from an array via System.arrayCopy for example, but you cannot alter the size. A list is a much better solution however.
– TofuBeer
Mar 13 '09 at 14:45
@Tom: Whether LinkedList is the correct choice depends on other factors too. "Random access", i.e. accessing a linked list via an index, is O(n).
– Todd Owen
Jul 16 '10 at 7:02
|
show 3 more comments
Nice looking solution would be to use a List instead of array in the first place.
List.remove(index)
If you have to use arrays, two calls to System.arraycopy
will most likely be the fastest.
Foo result = new Foo[source.length - 1];
System.arraycopy(source, 0, result, 0, index);
if (source.length != index) {
System.arraycopy(source, index + 1, result, index, source.length - index - 1);
}
(Arrays.asList
is also a good candidate for working with arrays, but it doesn't seem to support remove
.)
1
+1: Use LinkedList or ArrayList.
– S.Lott
Mar 13 '09 at 14:18
add a comment |
I think the question was asking for a solution without the use of the Collections API. One uses arrays either for low level details, where performance matters, or for a loosely coupled SOA integration. In the later, it is OK to convert them to Collections and pass them to the business logic as that.
For the low level performance stuff, it is usually already obfuscated by the quick-and-dirty imperative state-mingling by for loops, etc. In that case converting back and forth between Collections and arrays is cumbersome, unreadable, and even resource intensive.
By the way, TopCoder, anyone? Always those array parameters! So be prepared to be able to handle them when in the Arena.
Below is my interpretation of the problem, and a solution. It is different in functionality from both of the one given by Bill K and jelovirt. Also, it handles gracefully the case when the element is not in the array.
Hope that helps!
public char remove(char symbols, char c)
{
for (int i = 0; i < symbols.length; i++)
{
if (symbols[i] == c)
{
char copy = new char[symbols.length-1];
System.arraycopy(symbols, 0, copy, 0, i);
System.arraycopy(symbols, i+1, copy, i, symbols.length-i-1);
return copy;
}
}
return symbols;
}
1
This is working perfectly.
– Reddy
Oct 22 '10 at 7:12
1
Great. Too many responses answering a different question to OP's.
– Return_Of_The_Archons
May 12 '17 at 13:41
add a comment |
You could use the ArrayUtils API to remove it in a "nice looking way". It implements many operations (remove, find, add, contains,etc) on Arrays.
Take a look. It has made my life simpler.
add a comment |
Some more pre-conditions are needed for the ones written by Bill K and dadinn
Object newArray = new Object[src.length - 1];
if (i > 0){
System.arraycopy(src, 0, newArray, 0, i);
}
if (newArray.length > i){
System.arraycopy(src, i + 1, newArray, i, newArray.length - i);
}
return newArray;
add a comment |
You can not change the length of an array, but you can change the values the index holds by copying new values and store them to a existing index number.
1=mike , 2=jeff // 10 = george 11 goes to 1 overwriting mike .
Object array = new Object[10];
int count = -1;
public void myFunction(String string) {
count++;
if(count == array.length) {
count = 0; // overwrite first
}
array[count] = string;
}
1
I think pointing out, that the length of an array can not be changed is an important detail!
– Torsten Robitzki
Jan 14 '16 at 12:45
add a comment |
okay, thx a lot
now i use sth like this:
public static String removeElements(String input, String deleteMe) {
if (input != null) {
List<String> list = new ArrayList<String>(Arrays.asList(input));
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(deleteMe)) {
list.remove(i);
}
}
return list.toArray(new String[0]);
} else {
return new String[0];
}
}
If you really need to leave the inital array unchanged, you'd better create an empty list and fill it with the right elements rather than doing it this way.
– Nicolas
Mar 13 '09 at 15:02
I'm not sure this is what people had in mind when they suggested using collections, but at any rate, be careful with those list indices. It looks like you're skipping the element immediately following any removal (try {"a", "b", "deleteMe", "deleteMe", "c"}).
– Sam Martin
Mar 13 '09 at 15:05
add a comment |
Copy your original array into another array, without the element to be removed.
A simplier way to do that is to use a List, Set... and use the remove() method.
add a comment |
Swap the item to be removed with the last item, if resizing the array down is not an interest.
2
This would break things if the array was sorted prior to the remove.
– eleven81
Mar 13 '09 at 14:32
add a comment |
I hope you use the java collection / java commons collections!
With an java.util.ArrayList you can do things like the following:
yourArrayList.remove(someObject);
yourArrayList.add(someObject);
2
An array is not a collection...
– Nicolas
Mar 13 '09 at 14:17
But the most collections are arrays! See: en.wikipedia.org/wiki/Array
– Martin K.
Mar 13 '09 at 14:21
1
Yep, but this question is java tagged and, in java, an array is not a collection...
– Nicolas
Mar 13 '09 at 14:24
I don't start to fight a religious war about what is a collection of elements and what isn't. Writing Java with a lot of procedural elements is bad! Take profit from the OO fatures! You can create nearly every collection from the Java Array construct.
– Martin K.
Mar 13 '09 at 14:27
1
I don't see why this guy is being modded down. If you need to be able to easily remove an element from an ordered group, then it's pretty clear that perhaps an array is the wrong kind of group to use in the first place. So List is a good suggestion, and Set might be better, depending on the app.
– Ben Hardy
Mar 13 '09 at 23:41
|
show 5 more comments
Use an ArrayList
:
alist.remove(1); //removes the element at position 1
add a comment |
Sure, create another array :)
add a comment |
15 Answers
15
active
oldest
votes
15 Answers
15
active
oldest
votes
active
oldest
votes
active
oldest
votes
You could use commons lang's ArrayUtils.
array = ArrayUtils.removeElement(array, element)
commons.apache.org library:Javadocs
1
@Clive Guava appears to only work on collections.
– Peter Lawrey
Mar 23 '14 at 7:33
3
does this shrink the array as well?
– Supun Wijerathne
Aug 5 '16 at 8:36
1
@SupunWijerathne it has to, to change the size/length.
– Peter Lawrey
Aug 5 '16 at 9:36
1
It is not working in Java8 and I am not getting any method with the nameremoveElement
– Atul Agrawal
Feb 16 at 8:12
1
ArrayUtils.remove if you want to specify an index, not the value itself
– Line
Dec 10 at 14:43
|
show 2 more comments
You could use commons lang's ArrayUtils.
array = ArrayUtils.removeElement(array, element)
commons.apache.org library:Javadocs
1
@Clive Guava appears to only work on collections.
– Peter Lawrey
Mar 23 '14 at 7:33
3
does this shrink the array as well?
– Supun Wijerathne
Aug 5 '16 at 8:36
1
@SupunWijerathne it has to, to change the size/length.
– Peter Lawrey
Aug 5 '16 at 9:36
1
It is not working in Java8 and I am not getting any method with the nameremoveElement
– Atul Agrawal
Feb 16 at 8:12
1
ArrayUtils.remove if you want to specify an index, not the value itself
– Line
Dec 10 at 14:43
|
show 2 more comments
You could use commons lang's ArrayUtils.
array = ArrayUtils.removeElement(array, element)
commons.apache.org library:Javadocs
You could use commons lang's ArrayUtils.
array = ArrayUtils.removeElement(array, element)
commons.apache.org library:Javadocs
edited Aug 9 '16 at 12:51
Abhijeet
4,94814663
4,94814663
answered Mar 13 '09 at 21:40
Peter Lawrey
440k55558958
440k55558958
1
@Clive Guava appears to only work on collections.
– Peter Lawrey
Mar 23 '14 at 7:33
3
does this shrink the array as well?
– Supun Wijerathne
Aug 5 '16 at 8:36
1
@SupunWijerathne it has to, to change the size/length.
– Peter Lawrey
Aug 5 '16 at 9:36
1
It is not working in Java8 and I am not getting any method with the nameremoveElement
– Atul Agrawal
Feb 16 at 8:12
1
ArrayUtils.remove if you want to specify an index, not the value itself
– Line
Dec 10 at 14:43
|
show 2 more comments
1
@Clive Guava appears to only work on collections.
– Peter Lawrey
Mar 23 '14 at 7:33
3
does this shrink the array as well?
– Supun Wijerathne
Aug 5 '16 at 8:36
1
@SupunWijerathne it has to, to change the size/length.
– Peter Lawrey
Aug 5 '16 at 9:36
1
It is not working in Java8 and I am not getting any method with the nameremoveElement
– Atul Agrawal
Feb 16 at 8:12
1
ArrayUtils.remove if you want to specify an index, not the value itself
– Line
Dec 10 at 14:43
1
1
@Clive Guava appears to only work on collections.
– Peter Lawrey
Mar 23 '14 at 7:33
@Clive Guava appears to only work on collections.
– Peter Lawrey
Mar 23 '14 at 7:33
3
3
does this shrink the array as well?
– Supun Wijerathne
Aug 5 '16 at 8:36
does this shrink the array as well?
– Supun Wijerathne
Aug 5 '16 at 8:36
1
1
@SupunWijerathne it has to, to change the size/length.
– Peter Lawrey
Aug 5 '16 at 9:36
@SupunWijerathne it has to, to change the size/length.
– Peter Lawrey
Aug 5 '16 at 9:36
1
1
It is not working in Java8 and I am not getting any method with the name
removeElement
– Atul Agrawal
Feb 16 at 8:12
It is not working in Java8 and I am not getting any method with the name
removeElement
– Atul Agrawal
Feb 16 at 8:12
1
1
ArrayUtils.remove if you want to specify an index, not the value itself
– Line
Dec 10 at 14:43
ArrayUtils.remove if you want to specify an index, not the value itself
– Line
Dec 10 at 14:43
|
show 2 more comments
Your question isn't very clear. From your own answer, I can tell better what you are trying to do:
public static String removeElements(String input, String deleteMe) {
List result = new LinkedList();
for(String item : input)
if(!deleteMe.equals(item))
result.add(item);
return result.toArray(input);
}
NB: This is untested. Error checking is left as an exercise to the reader (I'd throw IllegalArgumentException if either input or deleteMe is null; an empty list on null list input doesn't make sense. Removing null Strings from the array might make sense, but I'll leave that as an exercise too; currently, it will throw an NPE when it tries to call equals on deleteMe if deleteMe is null.)
Choices I made here:
I used a LinkedList. Iteration should be just as fast, and you avoid any resizes, or allocating too big of a list if you end up deleting lots of elements. You could use an ArrayList, and set the initial size to the length of input. It likely wouldn't make much of a difference.
2
Note, you'll want to useList<String>
result. When I do this in the current compiler, the toArray command gives a type error (the other solution is to cast the result.)
– user1086498
May 27 '13 at 11:28
add a comment |
Your question isn't very clear. From your own answer, I can tell better what you are trying to do:
public static String removeElements(String input, String deleteMe) {
List result = new LinkedList();
for(String item : input)
if(!deleteMe.equals(item))
result.add(item);
return result.toArray(input);
}
NB: This is untested. Error checking is left as an exercise to the reader (I'd throw IllegalArgumentException if either input or deleteMe is null; an empty list on null list input doesn't make sense. Removing null Strings from the array might make sense, but I'll leave that as an exercise too; currently, it will throw an NPE when it tries to call equals on deleteMe if deleteMe is null.)
Choices I made here:
I used a LinkedList. Iteration should be just as fast, and you avoid any resizes, or allocating too big of a list if you end up deleting lots of elements. You could use an ArrayList, and set the initial size to the length of input. It likely wouldn't make much of a difference.
2
Note, you'll want to useList<String>
result. When I do this in the current compiler, the toArray command gives a type error (the other solution is to cast the result.)
– user1086498
May 27 '13 at 11:28
add a comment |
Your question isn't very clear. From your own answer, I can tell better what you are trying to do:
public static String removeElements(String input, String deleteMe) {
List result = new LinkedList();
for(String item : input)
if(!deleteMe.equals(item))
result.add(item);
return result.toArray(input);
}
NB: This is untested. Error checking is left as an exercise to the reader (I'd throw IllegalArgumentException if either input or deleteMe is null; an empty list on null list input doesn't make sense. Removing null Strings from the array might make sense, but I'll leave that as an exercise too; currently, it will throw an NPE when it tries to call equals on deleteMe if deleteMe is null.)
Choices I made here:
I used a LinkedList. Iteration should be just as fast, and you avoid any resizes, or allocating too big of a list if you end up deleting lots of elements. You could use an ArrayList, and set the initial size to the length of input. It likely wouldn't make much of a difference.
Your question isn't very clear. From your own answer, I can tell better what you are trying to do:
public static String removeElements(String input, String deleteMe) {
List result = new LinkedList();
for(String item : input)
if(!deleteMe.equals(item))
result.add(item);
return result.toArray(input);
}
NB: This is untested. Error checking is left as an exercise to the reader (I'd throw IllegalArgumentException if either input or deleteMe is null; an empty list on null list input doesn't make sense. Removing null Strings from the array might make sense, but I'll leave that as an exercise too; currently, it will throw an NPE when it tries to call equals on deleteMe if deleteMe is null.)
Choices I made here:
I used a LinkedList. Iteration should be just as fast, and you avoid any resizes, or allocating too big of a list if you end up deleting lots of elements. You could use an ArrayList, and set the initial size to the length of input. It likely wouldn't make much of a difference.
answered Mar 13 '09 at 22:36
Adam Jaskiewicz
9,96032731
9,96032731
2
Note, you'll want to useList<String>
result. When I do this in the current compiler, the toArray command gives a type error (the other solution is to cast the result.)
– user1086498
May 27 '13 at 11:28
add a comment |
2
Note, you'll want to useList<String>
result. When I do this in the current compiler, the toArray command gives a type error (the other solution is to cast the result.)
– user1086498
May 27 '13 at 11:28
2
2
Note, you'll want to use
List<String>
result. When I do this in the current compiler, the toArray command gives a type error (the other solution is to cast the result.)– user1086498
May 27 '13 at 11:28
Note, you'll want to use
List<String>
result. When I do this in the current compiler, the toArray command gives a type error (the other solution is to cast the result.)– user1086498
May 27 '13 at 11:28
add a comment |
The best choice would be to use a collection, but if that is out for some reason, use arraycopy
. You can use it to copy from and to the same array at a slightly different offset.
For example:
public void removeElement(Object arr, int removedIdx) {
System.arraycopy(arr, removedIdx + 1, arr, removedIdx, arr.length - 1 - removedIdx);
}
Edit in response to comment (tl;dr):
It's not another good way, it's really the only acceptable way--any tools that allow this functionality (like Java.ArrayList or the apache utils) will use this method under the covers. Also, you REALLY should be using ArrayList (or linked list if you delete from the middle a lot) so this shouldn't even be an issue unless you are doing it as homework.
To allocate a collection (creates a new array), then delete an element (which the collection will do using arraycopy) then call toArray on it (creates a SECOND new array) for every delete brings us to the point where it's not an optimizing issue, it's criminally bad programming.
Suppose you had an array taking up, say, 100mb of ram. Now you want to iterate over it and delete 20 elements.
Give it a try...
I know you ASSUME that it's not going to be that big, or that if you were deleting that many at once you'd code it differently, but I've fixed an awful lot of code where someone made assumptions like that.
2
Following a "deletion" (i.e. shifting the array left by one element) won't there be a duplicate of the end element? i.e. a.length will be the same following the deletion, no? I'm not saying I dislike the idea, just that one needs to be aware of this.
– Adamski
Aug 13 '10 at 12:55
+1. This works for my purposes. (I fixed the small issue you had in your sample. Hope you don't mind.)
– Gunslinger47
Sep 25 '10 at 6:12
Yes, this will just shift the elements left and there will be last element still present. We have to use new array to copy.
– Reddy
Oct 22 '10 at 6:33
BTW, this is what org.apache.commons.lang.ArrayUtils does too.
– Reddy
Oct 22 '10 at 6:34
It's assumed that if you are adding and deleting elements from an array you are also tracking the "Last" item in the array, so copying shouldn't be necessary.
– Bill K
Feb 23 '11 at 20:43
add a comment |
The best choice would be to use a collection, but if that is out for some reason, use arraycopy
. You can use it to copy from and to the same array at a slightly different offset.
For example:
public void removeElement(Object arr, int removedIdx) {
System.arraycopy(arr, removedIdx + 1, arr, removedIdx, arr.length - 1 - removedIdx);
}
Edit in response to comment (tl;dr):
It's not another good way, it's really the only acceptable way--any tools that allow this functionality (like Java.ArrayList or the apache utils) will use this method under the covers. Also, you REALLY should be using ArrayList (or linked list if you delete from the middle a lot) so this shouldn't even be an issue unless you are doing it as homework.
To allocate a collection (creates a new array), then delete an element (which the collection will do using arraycopy) then call toArray on it (creates a SECOND new array) for every delete brings us to the point where it's not an optimizing issue, it's criminally bad programming.
Suppose you had an array taking up, say, 100mb of ram. Now you want to iterate over it and delete 20 elements.
Give it a try...
I know you ASSUME that it's not going to be that big, or that if you were deleting that many at once you'd code it differently, but I've fixed an awful lot of code where someone made assumptions like that.
2
Following a "deletion" (i.e. shifting the array left by one element) won't there be a duplicate of the end element? i.e. a.length will be the same following the deletion, no? I'm not saying I dislike the idea, just that one needs to be aware of this.
– Adamski
Aug 13 '10 at 12:55
+1. This works for my purposes. (I fixed the small issue you had in your sample. Hope you don't mind.)
– Gunslinger47
Sep 25 '10 at 6:12
Yes, this will just shift the elements left and there will be last element still present. We have to use new array to copy.
– Reddy
Oct 22 '10 at 6:33
BTW, this is what org.apache.commons.lang.ArrayUtils does too.
– Reddy
Oct 22 '10 at 6:34
It's assumed that if you are adding and deleting elements from an array you are also tracking the "Last" item in the array, so copying shouldn't be necessary.
– Bill K
Feb 23 '11 at 20:43
add a comment |
The best choice would be to use a collection, but if that is out for some reason, use arraycopy
. You can use it to copy from and to the same array at a slightly different offset.
For example:
public void removeElement(Object arr, int removedIdx) {
System.arraycopy(arr, removedIdx + 1, arr, removedIdx, arr.length - 1 - removedIdx);
}
Edit in response to comment (tl;dr):
It's not another good way, it's really the only acceptable way--any tools that allow this functionality (like Java.ArrayList or the apache utils) will use this method under the covers. Also, you REALLY should be using ArrayList (or linked list if you delete from the middle a lot) so this shouldn't even be an issue unless you are doing it as homework.
To allocate a collection (creates a new array), then delete an element (which the collection will do using arraycopy) then call toArray on it (creates a SECOND new array) for every delete brings us to the point where it's not an optimizing issue, it's criminally bad programming.
Suppose you had an array taking up, say, 100mb of ram. Now you want to iterate over it and delete 20 elements.
Give it a try...
I know you ASSUME that it's not going to be that big, or that if you were deleting that many at once you'd code it differently, but I've fixed an awful lot of code where someone made assumptions like that.
The best choice would be to use a collection, but if that is out for some reason, use arraycopy
. You can use it to copy from and to the same array at a slightly different offset.
For example:
public void removeElement(Object arr, int removedIdx) {
System.arraycopy(arr, removedIdx + 1, arr, removedIdx, arr.length - 1 - removedIdx);
}
Edit in response to comment (tl;dr):
It's not another good way, it's really the only acceptable way--any tools that allow this functionality (like Java.ArrayList or the apache utils) will use this method under the covers. Also, you REALLY should be using ArrayList (or linked list if you delete from the middle a lot) so this shouldn't even be an issue unless you are doing it as homework.
To allocate a collection (creates a new array), then delete an element (which the collection will do using arraycopy) then call toArray on it (creates a SECOND new array) for every delete brings us to the point where it's not an optimizing issue, it's criminally bad programming.
Suppose you had an array taking up, say, 100mb of ram. Now you want to iterate over it and delete 20 elements.
Give it a try...
I know you ASSUME that it's not going to be that big, or that if you were deleting that many at once you'd code it differently, but I've fixed an awful lot of code where someone made assumptions like that.
edited Oct 22 at 17:33
answered Mar 13 '09 at 21:55
Bill K
53k1385137
53k1385137
2
Following a "deletion" (i.e. shifting the array left by one element) won't there be a duplicate of the end element? i.e. a.length will be the same following the deletion, no? I'm not saying I dislike the idea, just that one needs to be aware of this.
– Adamski
Aug 13 '10 at 12:55
+1. This works for my purposes. (I fixed the small issue you had in your sample. Hope you don't mind.)
– Gunslinger47
Sep 25 '10 at 6:12
Yes, this will just shift the elements left and there will be last element still present. We have to use new array to copy.
– Reddy
Oct 22 '10 at 6:33
BTW, this is what org.apache.commons.lang.ArrayUtils does too.
– Reddy
Oct 22 '10 at 6:34
It's assumed that if you are adding and deleting elements from an array you are also tracking the "Last" item in the array, so copying shouldn't be necessary.
– Bill K
Feb 23 '11 at 20:43
add a comment |
2
Following a "deletion" (i.e. shifting the array left by one element) won't there be a duplicate of the end element? i.e. a.length will be the same following the deletion, no? I'm not saying I dislike the idea, just that one needs to be aware of this.
– Adamski
Aug 13 '10 at 12:55
+1. This works for my purposes. (I fixed the small issue you had in your sample. Hope you don't mind.)
– Gunslinger47
Sep 25 '10 at 6:12
Yes, this will just shift the elements left and there will be last element still present. We have to use new array to copy.
– Reddy
Oct 22 '10 at 6:33
BTW, this is what org.apache.commons.lang.ArrayUtils does too.
– Reddy
Oct 22 '10 at 6:34
It's assumed that if you are adding and deleting elements from an array you are also tracking the "Last" item in the array, so copying shouldn't be necessary.
– Bill K
Feb 23 '11 at 20:43
2
2
Following a "deletion" (i.e. shifting the array left by one element) won't there be a duplicate of the end element? i.e. a.length will be the same following the deletion, no? I'm not saying I dislike the idea, just that one needs to be aware of this.
– Adamski
Aug 13 '10 at 12:55
Following a "deletion" (i.e. shifting the array left by one element) won't there be a duplicate of the end element? i.e. a.length will be the same following the deletion, no? I'm not saying I dislike the idea, just that one needs to be aware of this.
– Adamski
Aug 13 '10 at 12:55
+1. This works for my purposes. (I fixed the small issue you had in your sample. Hope you don't mind.)
– Gunslinger47
Sep 25 '10 at 6:12
+1. This works for my purposes. (I fixed the small issue you had in your sample. Hope you don't mind.)
– Gunslinger47
Sep 25 '10 at 6:12
Yes, this will just shift the elements left and there will be last element still present. We have to use new array to copy.
– Reddy
Oct 22 '10 at 6:33
Yes, this will just shift the elements left and there will be last element still present. We have to use new array to copy.
– Reddy
Oct 22 '10 at 6:33
BTW, this is what org.apache.commons.lang.ArrayUtils does too.
– Reddy
Oct 22 '10 at 6:34
BTW, this is what org.apache.commons.lang.ArrayUtils does too.
– Reddy
Oct 22 '10 at 6:34
It's assumed that if you are adding and deleting elements from an array you are also tracking the "Last" item in the array, so copying shouldn't be necessary.
– Bill K
Feb 23 '11 at 20:43
It's assumed that if you are adding and deleting elements from an array you are also tracking the "Last" item in the array, so copying shouldn't be necessary.
– Bill K
Feb 23 '11 at 20:43
add a comment |
You can't remove an element from the basic Java array. Take a look at various Collections and ArrayList instead.
i know, i just want a beautiful looking way with arraylists or sth. like that, any hint for that?
– Tobias
Mar 13 '09 at 14:15
+1: Use LinkedList, life is simpler.
– S.Lott
Mar 13 '09 at 14:17
7
LinkedList is rarely a good idea. The List intrrface gives you random access, but LinkedList gives O(n) access times instead of O(1).
– Tom Hawtin - tackline
Mar 13 '09 at 14:24
1
You can remove an element from an array via System.arrayCopy for example, but you cannot alter the size. A list is a much better solution however.
– TofuBeer
Mar 13 '09 at 14:45
@Tom: Whether LinkedList is the correct choice depends on other factors too. "Random access", i.e. accessing a linked list via an index, is O(n).
– Todd Owen
Jul 16 '10 at 7:02
|
show 3 more comments
You can't remove an element from the basic Java array. Take a look at various Collections and ArrayList instead.
i know, i just want a beautiful looking way with arraylists or sth. like that, any hint for that?
– Tobias
Mar 13 '09 at 14:15
+1: Use LinkedList, life is simpler.
– S.Lott
Mar 13 '09 at 14:17
7
LinkedList is rarely a good idea. The List intrrface gives you random access, but LinkedList gives O(n) access times instead of O(1).
– Tom Hawtin - tackline
Mar 13 '09 at 14:24
1
You can remove an element from an array via System.arrayCopy for example, but you cannot alter the size. A list is a much better solution however.
– TofuBeer
Mar 13 '09 at 14:45
@Tom: Whether LinkedList is the correct choice depends on other factors too. "Random access", i.e. accessing a linked list via an index, is O(n).
– Todd Owen
Jul 16 '10 at 7:02
|
show 3 more comments
You can't remove an element from the basic Java array. Take a look at various Collections and ArrayList instead.
You can't remove an element from the basic Java array. Take a look at various Collections and ArrayList instead.
answered Mar 13 '09 at 14:13
Vlad Gudim
16.6k146291
16.6k146291
i know, i just want a beautiful looking way with arraylists or sth. like that, any hint for that?
– Tobias
Mar 13 '09 at 14:15
+1: Use LinkedList, life is simpler.
– S.Lott
Mar 13 '09 at 14:17
7
LinkedList is rarely a good idea. The List intrrface gives you random access, but LinkedList gives O(n) access times instead of O(1).
– Tom Hawtin - tackline
Mar 13 '09 at 14:24
1
You can remove an element from an array via System.arrayCopy for example, but you cannot alter the size. A list is a much better solution however.
– TofuBeer
Mar 13 '09 at 14:45
@Tom: Whether LinkedList is the correct choice depends on other factors too. "Random access", i.e. accessing a linked list via an index, is O(n).
– Todd Owen
Jul 16 '10 at 7:02
|
show 3 more comments
i know, i just want a beautiful looking way with arraylists or sth. like that, any hint for that?
– Tobias
Mar 13 '09 at 14:15
+1: Use LinkedList, life is simpler.
– S.Lott
Mar 13 '09 at 14:17
7
LinkedList is rarely a good idea. The List intrrface gives you random access, but LinkedList gives O(n) access times instead of O(1).
– Tom Hawtin - tackline
Mar 13 '09 at 14:24
1
You can remove an element from an array via System.arrayCopy for example, but you cannot alter the size. A list is a much better solution however.
– TofuBeer
Mar 13 '09 at 14:45
@Tom: Whether LinkedList is the correct choice depends on other factors too. "Random access", i.e. accessing a linked list via an index, is O(n).
– Todd Owen
Jul 16 '10 at 7:02
i know, i just want a beautiful looking way with arraylists or sth. like that, any hint for that?
– Tobias
Mar 13 '09 at 14:15
i know, i just want a beautiful looking way with arraylists or sth. like that, any hint for that?
– Tobias
Mar 13 '09 at 14:15
+1: Use LinkedList, life is simpler.
– S.Lott
Mar 13 '09 at 14:17
+1: Use LinkedList, life is simpler.
– S.Lott
Mar 13 '09 at 14:17
7
7
LinkedList is rarely a good idea. The List intrrface gives you random access, but LinkedList gives O(n) access times instead of O(1).
– Tom Hawtin - tackline
Mar 13 '09 at 14:24
LinkedList is rarely a good idea. The List intrrface gives you random access, but LinkedList gives O(n) access times instead of O(1).
– Tom Hawtin - tackline
Mar 13 '09 at 14:24
1
1
You can remove an element from an array via System.arrayCopy for example, but you cannot alter the size. A list is a much better solution however.
– TofuBeer
Mar 13 '09 at 14:45
You can remove an element from an array via System.arrayCopy for example, but you cannot alter the size. A list is a much better solution however.
– TofuBeer
Mar 13 '09 at 14:45
@Tom: Whether LinkedList is the correct choice depends on other factors too. "Random access", i.e. accessing a linked list via an index, is O(n).
– Todd Owen
Jul 16 '10 at 7:02
@Tom: Whether LinkedList is the correct choice depends on other factors too. "Random access", i.e. accessing a linked list via an index, is O(n).
– Todd Owen
Jul 16 '10 at 7:02
|
show 3 more comments
Nice looking solution would be to use a List instead of array in the first place.
List.remove(index)
If you have to use arrays, two calls to System.arraycopy
will most likely be the fastest.
Foo result = new Foo[source.length - 1];
System.arraycopy(source, 0, result, 0, index);
if (source.length != index) {
System.arraycopy(source, index + 1, result, index, source.length - index - 1);
}
(Arrays.asList
is also a good candidate for working with arrays, but it doesn't seem to support remove
.)
1
+1: Use LinkedList or ArrayList.
– S.Lott
Mar 13 '09 at 14:18
add a comment |
Nice looking solution would be to use a List instead of array in the first place.
List.remove(index)
If you have to use arrays, two calls to System.arraycopy
will most likely be the fastest.
Foo result = new Foo[source.length - 1];
System.arraycopy(source, 0, result, 0, index);
if (source.length != index) {
System.arraycopy(source, index + 1, result, index, source.length - index - 1);
}
(Arrays.asList
is also a good candidate for working with arrays, but it doesn't seem to support remove
.)
1
+1: Use LinkedList or ArrayList.
– S.Lott
Mar 13 '09 at 14:18
add a comment |
Nice looking solution would be to use a List instead of array in the first place.
List.remove(index)
If you have to use arrays, two calls to System.arraycopy
will most likely be the fastest.
Foo result = new Foo[source.length - 1];
System.arraycopy(source, 0, result, 0, index);
if (source.length != index) {
System.arraycopy(source, index + 1, result, index, source.length - index - 1);
}
(Arrays.asList
is also a good candidate for working with arrays, but it doesn't seem to support remove
.)
Nice looking solution would be to use a List instead of array in the first place.
List.remove(index)
If you have to use arrays, two calls to System.arraycopy
will most likely be the fastest.
Foo result = new Foo[source.length - 1];
System.arraycopy(source, 0, result, 0, index);
if (source.length != index) {
System.arraycopy(source, index + 1, result, index, source.length - index - 1);
}
(Arrays.asList
is also a good candidate for working with arrays, but it doesn't seem to support remove
.)
edited Mar 13 '09 at 16:46
answered Mar 13 '09 at 14:15
jelovirt
4,55283348
4,55283348
1
+1: Use LinkedList or ArrayList.
– S.Lott
Mar 13 '09 at 14:18
add a comment |
1
+1: Use LinkedList or ArrayList.
– S.Lott
Mar 13 '09 at 14:18
1
1
+1: Use LinkedList or ArrayList.
– S.Lott
Mar 13 '09 at 14:18
+1: Use LinkedList or ArrayList.
– S.Lott
Mar 13 '09 at 14:18
add a comment |
I think the question was asking for a solution without the use of the Collections API. One uses arrays either for low level details, where performance matters, or for a loosely coupled SOA integration. In the later, it is OK to convert them to Collections and pass them to the business logic as that.
For the low level performance stuff, it is usually already obfuscated by the quick-and-dirty imperative state-mingling by for loops, etc. In that case converting back and forth between Collections and arrays is cumbersome, unreadable, and even resource intensive.
By the way, TopCoder, anyone? Always those array parameters! So be prepared to be able to handle them when in the Arena.
Below is my interpretation of the problem, and a solution. It is different in functionality from both of the one given by Bill K and jelovirt. Also, it handles gracefully the case when the element is not in the array.
Hope that helps!
public char remove(char symbols, char c)
{
for (int i = 0; i < symbols.length; i++)
{
if (symbols[i] == c)
{
char copy = new char[symbols.length-1];
System.arraycopy(symbols, 0, copy, 0, i);
System.arraycopy(symbols, i+1, copy, i, symbols.length-i-1);
return copy;
}
}
return symbols;
}
1
This is working perfectly.
– Reddy
Oct 22 '10 at 7:12
1
Great. Too many responses answering a different question to OP's.
– Return_Of_The_Archons
May 12 '17 at 13:41
add a comment |
I think the question was asking for a solution without the use of the Collections API. One uses arrays either for low level details, where performance matters, or for a loosely coupled SOA integration. In the later, it is OK to convert them to Collections and pass them to the business logic as that.
For the low level performance stuff, it is usually already obfuscated by the quick-and-dirty imperative state-mingling by for loops, etc. In that case converting back and forth between Collections and arrays is cumbersome, unreadable, and even resource intensive.
By the way, TopCoder, anyone? Always those array parameters! So be prepared to be able to handle them when in the Arena.
Below is my interpretation of the problem, and a solution. It is different in functionality from both of the one given by Bill K and jelovirt. Also, it handles gracefully the case when the element is not in the array.
Hope that helps!
public char remove(char symbols, char c)
{
for (int i = 0; i < symbols.length; i++)
{
if (symbols[i] == c)
{
char copy = new char[symbols.length-1];
System.arraycopy(symbols, 0, copy, 0, i);
System.arraycopy(symbols, i+1, copy, i, symbols.length-i-1);
return copy;
}
}
return symbols;
}
1
This is working perfectly.
– Reddy
Oct 22 '10 at 7:12
1
Great. Too many responses answering a different question to OP's.
– Return_Of_The_Archons
May 12 '17 at 13:41
add a comment |
I think the question was asking for a solution without the use of the Collections API. One uses arrays either for low level details, where performance matters, or for a loosely coupled SOA integration. In the later, it is OK to convert them to Collections and pass them to the business logic as that.
For the low level performance stuff, it is usually already obfuscated by the quick-and-dirty imperative state-mingling by for loops, etc. In that case converting back and forth between Collections and arrays is cumbersome, unreadable, and even resource intensive.
By the way, TopCoder, anyone? Always those array parameters! So be prepared to be able to handle them when in the Arena.
Below is my interpretation of the problem, and a solution. It is different in functionality from both of the one given by Bill K and jelovirt. Also, it handles gracefully the case when the element is not in the array.
Hope that helps!
public char remove(char symbols, char c)
{
for (int i = 0; i < symbols.length; i++)
{
if (symbols[i] == c)
{
char copy = new char[symbols.length-1];
System.arraycopy(symbols, 0, copy, 0, i);
System.arraycopy(symbols, i+1, copy, i, symbols.length-i-1);
return copy;
}
}
return symbols;
}
I think the question was asking for a solution without the use of the Collections API. One uses arrays either for low level details, where performance matters, or for a loosely coupled SOA integration. In the later, it is OK to convert them to Collections and pass them to the business logic as that.
For the low level performance stuff, it is usually already obfuscated by the quick-and-dirty imperative state-mingling by for loops, etc. In that case converting back and forth between Collections and arrays is cumbersome, unreadable, and even resource intensive.
By the way, TopCoder, anyone? Always those array parameters! So be prepared to be able to handle them when in the Arena.
Below is my interpretation of the problem, and a solution. It is different in functionality from both of the one given by Bill K and jelovirt. Also, it handles gracefully the case when the element is not in the array.
Hope that helps!
public char remove(char symbols, char c)
{
for (int i = 0; i < symbols.length; i++)
{
if (symbols[i] == c)
{
char copy = new char[symbols.length-1];
System.arraycopy(symbols, 0, copy, 0, i);
System.arraycopy(symbols, i+1, copy, i, symbols.length-i-1);
return copy;
}
}
return symbols;
}
answered Aug 13 '10 at 12:40
Daniel Dinnyes
3,31622335
3,31622335
1
This is working perfectly.
– Reddy
Oct 22 '10 at 7:12
1
Great. Too many responses answering a different question to OP's.
– Return_Of_The_Archons
May 12 '17 at 13:41
add a comment |
1
This is working perfectly.
– Reddy
Oct 22 '10 at 7:12
1
Great. Too many responses answering a different question to OP's.
– Return_Of_The_Archons
May 12 '17 at 13:41
1
1
This is working perfectly.
– Reddy
Oct 22 '10 at 7:12
This is working perfectly.
– Reddy
Oct 22 '10 at 7:12
1
1
Great. Too many responses answering a different question to OP's.
– Return_Of_The_Archons
May 12 '17 at 13:41
Great. Too many responses answering a different question to OP's.
– Return_Of_The_Archons
May 12 '17 at 13:41
add a comment |
You could use the ArrayUtils API to remove it in a "nice looking way". It implements many operations (remove, find, add, contains,etc) on Arrays.
Take a look. It has made my life simpler.
add a comment |
You could use the ArrayUtils API to remove it in a "nice looking way". It implements many operations (remove, find, add, contains,etc) on Arrays.
Take a look. It has made my life simpler.
add a comment |
You could use the ArrayUtils API to remove it in a "nice looking way". It implements many operations (remove, find, add, contains,etc) on Arrays.
Take a look. It has made my life simpler.
You could use the ArrayUtils API to remove it in a "nice looking way". It implements many operations (remove, find, add, contains,etc) on Arrays.
Take a look. It has made my life simpler.
edited Nov 11 '11 at 18:00
christophercotton
5,00612746
5,00612746
answered Mar 14 '09 at 17:33
Tom
29.7k22116157
29.7k22116157
add a comment |
add a comment |
Some more pre-conditions are needed for the ones written by Bill K and dadinn
Object newArray = new Object[src.length - 1];
if (i > 0){
System.arraycopy(src, 0, newArray, 0, i);
}
if (newArray.length > i){
System.arraycopy(src, i + 1, newArray, i, newArray.length - i);
}
return newArray;
add a comment |
Some more pre-conditions are needed for the ones written by Bill K and dadinn
Object newArray = new Object[src.length - 1];
if (i > 0){
System.arraycopy(src, 0, newArray, 0, i);
}
if (newArray.length > i){
System.arraycopy(src, i + 1, newArray, i, newArray.length - i);
}
return newArray;
add a comment |
Some more pre-conditions are needed for the ones written by Bill K and dadinn
Object newArray = new Object[src.length - 1];
if (i > 0){
System.arraycopy(src, 0, newArray, 0, i);
}
if (newArray.length > i){
System.arraycopy(src, i + 1, newArray, i, newArray.length - i);
}
return newArray;
Some more pre-conditions are needed for the ones written by Bill K and dadinn
Object newArray = new Object[src.length - 1];
if (i > 0){
System.arraycopy(src, 0, newArray, 0, i);
}
if (newArray.length > i){
System.arraycopy(src, i + 1, newArray, i, newArray.length - i);
}
return newArray;
edited Apr 17 at 0:16
Lonely Neuron
2,86731732
2,86731732
answered Sep 9 '10 at 9:31
Binoy Joseph
291
291
add a comment |
add a comment |
You can not change the length of an array, but you can change the values the index holds by copying new values and store them to a existing index number.
1=mike , 2=jeff // 10 = george 11 goes to 1 overwriting mike .
Object array = new Object[10];
int count = -1;
public void myFunction(String string) {
count++;
if(count == array.length) {
count = 0; // overwrite first
}
array[count] = string;
}
1
I think pointing out, that the length of an array can not be changed is an important detail!
– Torsten Robitzki
Jan 14 '16 at 12:45
add a comment |
You can not change the length of an array, but you can change the values the index holds by copying new values and store them to a existing index number.
1=mike , 2=jeff // 10 = george 11 goes to 1 overwriting mike .
Object array = new Object[10];
int count = -1;
public void myFunction(String string) {
count++;
if(count == array.length) {
count = 0; // overwrite first
}
array[count] = string;
}
1
I think pointing out, that the length of an array can not be changed is an important detail!
– Torsten Robitzki
Jan 14 '16 at 12:45
add a comment |
You can not change the length of an array, but you can change the values the index holds by copying new values and store them to a existing index number.
1=mike , 2=jeff // 10 = george 11 goes to 1 overwriting mike .
Object array = new Object[10];
int count = -1;
public void myFunction(String string) {
count++;
if(count == array.length) {
count = 0; // overwrite first
}
array[count] = string;
}
You can not change the length of an array, but you can change the values the index holds by copying new values and store them to a existing index number.
1=mike , 2=jeff // 10 = george 11 goes to 1 overwriting mike .
Object array = new Object[10];
int count = -1;
public void myFunction(String string) {
count++;
if(count == array.length) {
count = 0; // overwrite first
}
array[count] = string;
}
edited Apr 17 at 0:17
Lonely Neuron
2,86731732
2,86731732
answered Oct 28 '12 at 18:17
Andre
12918
12918
1
I think pointing out, that the length of an array can not be changed is an important detail!
– Torsten Robitzki
Jan 14 '16 at 12:45
add a comment |
1
I think pointing out, that the length of an array can not be changed is an important detail!
– Torsten Robitzki
Jan 14 '16 at 12:45
1
1
I think pointing out, that the length of an array can not be changed is an important detail!
– Torsten Robitzki
Jan 14 '16 at 12:45
I think pointing out, that the length of an array can not be changed is an important detail!
– Torsten Robitzki
Jan 14 '16 at 12:45
add a comment |
okay, thx a lot
now i use sth like this:
public static String removeElements(String input, String deleteMe) {
if (input != null) {
List<String> list = new ArrayList<String>(Arrays.asList(input));
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(deleteMe)) {
list.remove(i);
}
}
return list.toArray(new String[0]);
} else {
return new String[0];
}
}
If you really need to leave the inital array unchanged, you'd better create an empty list and fill it with the right elements rather than doing it this way.
– Nicolas
Mar 13 '09 at 15:02
I'm not sure this is what people had in mind when they suggested using collections, but at any rate, be careful with those list indices. It looks like you're skipping the element immediately following any removal (try {"a", "b", "deleteMe", "deleteMe", "c"}).
– Sam Martin
Mar 13 '09 at 15:05
add a comment |
okay, thx a lot
now i use sth like this:
public static String removeElements(String input, String deleteMe) {
if (input != null) {
List<String> list = new ArrayList<String>(Arrays.asList(input));
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(deleteMe)) {
list.remove(i);
}
}
return list.toArray(new String[0]);
} else {
return new String[0];
}
}
If you really need to leave the inital array unchanged, you'd better create an empty list and fill it with the right elements rather than doing it this way.
– Nicolas
Mar 13 '09 at 15:02
I'm not sure this is what people had in mind when they suggested using collections, but at any rate, be careful with those list indices. It looks like you're skipping the element immediately following any removal (try {"a", "b", "deleteMe", "deleteMe", "c"}).
– Sam Martin
Mar 13 '09 at 15:05
add a comment |
okay, thx a lot
now i use sth like this:
public static String removeElements(String input, String deleteMe) {
if (input != null) {
List<String> list = new ArrayList<String>(Arrays.asList(input));
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(deleteMe)) {
list.remove(i);
}
}
return list.toArray(new String[0]);
} else {
return new String[0];
}
}
okay, thx a lot
now i use sth like this:
public static String removeElements(String input, String deleteMe) {
if (input != null) {
List<String> list = new ArrayList<String>(Arrays.asList(input));
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(deleteMe)) {
list.remove(i);
}
}
return list.toArray(new String[0]);
} else {
return new String[0];
}
}
answered Mar 13 '09 at 14:44
Tobias
4,68063764
4,68063764
If you really need to leave the inital array unchanged, you'd better create an empty list and fill it with the right elements rather than doing it this way.
– Nicolas
Mar 13 '09 at 15:02
I'm not sure this is what people had in mind when they suggested using collections, but at any rate, be careful with those list indices. It looks like you're skipping the element immediately following any removal (try {"a", "b", "deleteMe", "deleteMe", "c"}).
– Sam Martin
Mar 13 '09 at 15:05
add a comment |
If you really need to leave the inital array unchanged, you'd better create an empty list and fill it with the right elements rather than doing it this way.
– Nicolas
Mar 13 '09 at 15:02
I'm not sure this is what people had in mind when they suggested using collections, but at any rate, be careful with those list indices. It looks like you're skipping the element immediately following any removal (try {"a", "b", "deleteMe", "deleteMe", "c"}).
– Sam Martin
Mar 13 '09 at 15:05
If you really need to leave the inital array unchanged, you'd better create an empty list and fill it with the right elements rather than doing it this way.
– Nicolas
Mar 13 '09 at 15:02
If you really need to leave the inital array unchanged, you'd better create an empty list and fill it with the right elements rather than doing it this way.
– Nicolas
Mar 13 '09 at 15:02
I'm not sure this is what people had in mind when they suggested using collections, but at any rate, be careful with those list indices. It looks like you're skipping the element immediately following any removal (try {"a", "b", "deleteMe", "deleteMe", "c"}).
– Sam Martin
Mar 13 '09 at 15:05
I'm not sure this is what people had in mind when they suggested using collections, but at any rate, be careful with those list indices. It looks like you're skipping the element immediately following any removal (try {"a", "b", "deleteMe", "deleteMe", "c"}).
– Sam Martin
Mar 13 '09 at 15:05
add a comment |
Copy your original array into another array, without the element to be removed.
A simplier way to do that is to use a List, Set... and use the remove() method.
add a comment |
Copy your original array into another array, without the element to be removed.
A simplier way to do that is to use a List, Set... and use the remove() method.
add a comment |
Copy your original array into another array, without the element to be removed.
A simplier way to do that is to use a List, Set... and use the remove() method.
Copy your original array into another array, without the element to be removed.
A simplier way to do that is to use a List, Set... and use the remove() method.
answered Mar 13 '09 at 14:17
Romain Linsolas
59.4k41183257
59.4k41183257
add a comment |
add a comment |
Swap the item to be removed with the last item, if resizing the array down is not an interest.
2
This would break things if the array was sorted prior to the remove.
– eleven81
Mar 13 '09 at 14:32
add a comment |
Swap the item to be removed with the last item, if resizing the array down is not an interest.
2
This would break things if the array was sorted prior to the remove.
– eleven81
Mar 13 '09 at 14:32
add a comment |
Swap the item to be removed with the last item, if resizing the array down is not an interest.
Swap the item to be removed with the last item, if resizing the array down is not an interest.
answered Mar 13 '09 at 14:26
palindrom
9,35611323
9,35611323
2
This would break things if the array was sorted prior to the remove.
– eleven81
Mar 13 '09 at 14:32
add a comment |
2
This would break things if the array was sorted prior to the remove.
– eleven81
Mar 13 '09 at 14:32
2
2
This would break things if the array was sorted prior to the remove.
– eleven81
Mar 13 '09 at 14:32
This would break things if the array was sorted prior to the remove.
– eleven81
Mar 13 '09 at 14:32
add a comment |
I hope you use the java collection / java commons collections!
With an java.util.ArrayList you can do things like the following:
yourArrayList.remove(someObject);
yourArrayList.add(someObject);
2
An array is not a collection...
– Nicolas
Mar 13 '09 at 14:17
But the most collections are arrays! See: en.wikipedia.org/wiki/Array
– Martin K.
Mar 13 '09 at 14:21
1
Yep, but this question is java tagged and, in java, an array is not a collection...
– Nicolas
Mar 13 '09 at 14:24
I don't start to fight a religious war about what is a collection of elements and what isn't. Writing Java with a lot of procedural elements is bad! Take profit from the OO fatures! You can create nearly every collection from the Java Array construct.
– Martin K.
Mar 13 '09 at 14:27
1
I don't see why this guy is being modded down. If you need to be able to easily remove an element from an ordered group, then it's pretty clear that perhaps an array is the wrong kind of group to use in the first place. So List is a good suggestion, and Set might be better, depending on the app.
– Ben Hardy
Mar 13 '09 at 23:41
|
show 5 more comments
I hope you use the java collection / java commons collections!
With an java.util.ArrayList you can do things like the following:
yourArrayList.remove(someObject);
yourArrayList.add(someObject);
2
An array is not a collection...
– Nicolas
Mar 13 '09 at 14:17
But the most collections are arrays! See: en.wikipedia.org/wiki/Array
– Martin K.
Mar 13 '09 at 14:21
1
Yep, but this question is java tagged and, in java, an array is not a collection...
– Nicolas
Mar 13 '09 at 14:24
I don't start to fight a religious war about what is a collection of elements and what isn't. Writing Java with a lot of procedural elements is bad! Take profit from the OO fatures! You can create nearly every collection from the Java Array construct.
– Martin K.
Mar 13 '09 at 14:27
1
I don't see why this guy is being modded down. If you need to be able to easily remove an element from an ordered group, then it's pretty clear that perhaps an array is the wrong kind of group to use in the first place. So List is a good suggestion, and Set might be better, depending on the app.
– Ben Hardy
Mar 13 '09 at 23:41
|
show 5 more comments
I hope you use the java collection / java commons collections!
With an java.util.ArrayList you can do things like the following:
yourArrayList.remove(someObject);
yourArrayList.add(someObject);
I hope you use the java collection / java commons collections!
With an java.util.ArrayList you can do things like the following:
yourArrayList.remove(someObject);
yourArrayList.add(someObject);
edited Mar 13 '09 at 14:30
answered Mar 13 '09 at 14:16
Martin K.
3,54273046
3,54273046
2
An array is not a collection...
– Nicolas
Mar 13 '09 at 14:17
But the most collections are arrays! See: en.wikipedia.org/wiki/Array
– Martin K.
Mar 13 '09 at 14:21
1
Yep, but this question is java tagged and, in java, an array is not a collection...
– Nicolas
Mar 13 '09 at 14:24
I don't start to fight a religious war about what is a collection of elements and what isn't. Writing Java with a lot of procedural elements is bad! Take profit from the OO fatures! You can create nearly every collection from the Java Array construct.
– Martin K.
Mar 13 '09 at 14:27
1
I don't see why this guy is being modded down. If you need to be able to easily remove an element from an ordered group, then it's pretty clear that perhaps an array is the wrong kind of group to use in the first place. So List is a good suggestion, and Set might be better, depending on the app.
– Ben Hardy
Mar 13 '09 at 23:41
|
show 5 more comments
2
An array is not a collection...
– Nicolas
Mar 13 '09 at 14:17
But the most collections are arrays! See: en.wikipedia.org/wiki/Array
– Martin K.
Mar 13 '09 at 14:21
1
Yep, but this question is java tagged and, in java, an array is not a collection...
– Nicolas
Mar 13 '09 at 14:24
I don't start to fight a religious war about what is a collection of elements and what isn't. Writing Java with a lot of procedural elements is bad! Take profit from the OO fatures! You can create nearly every collection from the Java Array construct.
– Martin K.
Mar 13 '09 at 14:27
1
I don't see why this guy is being modded down. If you need to be able to easily remove an element from an ordered group, then it's pretty clear that perhaps an array is the wrong kind of group to use in the first place. So List is a good suggestion, and Set might be better, depending on the app.
– Ben Hardy
Mar 13 '09 at 23:41
2
2
An array is not a collection...
– Nicolas
Mar 13 '09 at 14:17
An array is not a collection...
– Nicolas
Mar 13 '09 at 14:17
But the most collections are arrays! See: en.wikipedia.org/wiki/Array
– Martin K.
Mar 13 '09 at 14:21
But the most collections are arrays! See: en.wikipedia.org/wiki/Array
– Martin K.
Mar 13 '09 at 14:21
1
1
Yep, but this question is java tagged and, in java, an array is not a collection...
– Nicolas
Mar 13 '09 at 14:24
Yep, but this question is java tagged and, in java, an array is not a collection...
– Nicolas
Mar 13 '09 at 14:24
I don't start to fight a religious war about what is a collection of elements and what isn't. Writing Java with a lot of procedural elements is bad! Take profit from the OO fatures! You can create nearly every collection from the Java Array construct.
– Martin K.
Mar 13 '09 at 14:27
I don't start to fight a religious war about what is a collection of elements and what isn't. Writing Java with a lot of procedural elements is bad! Take profit from the OO fatures! You can create nearly every collection from the Java Array construct.
– Martin K.
Mar 13 '09 at 14:27
1
1
I don't see why this guy is being modded down. If you need to be able to easily remove an element from an ordered group, then it's pretty clear that perhaps an array is the wrong kind of group to use in the first place. So List is a good suggestion, and Set might be better, depending on the app.
– Ben Hardy
Mar 13 '09 at 23:41
I don't see why this guy is being modded down. If you need to be able to easily remove an element from an ordered group, then it's pretty clear that perhaps an array is the wrong kind of group to use in the first place. So List is a good suggestion, and Set might be better, depending on the app.
– Ben Hardy
Mar 13 '09 at 23:41
|
show 5 more comments
Use an ArrayList
:
alist.remove(1); //removes the element at position 1
add a comment |
Use an ArrayList
:
alist.remove(1); //removes the element at position 1
add a comment |
Use an ArrayList
:
alist.remove(1); //removes the element at position 1
Use an ArrayList
:
alist.remove(1); //removes the element at position 1
answered Mar 13 '09 at 14:15
Andreas Grech
62.3k91272346
62.3k91272346
add a comment |
add a comment |
Sure, create another array :)
add a comment |
Sure, create another array :)
add a comment |
Sure, create another array :)
Sure, create another array :)
answered Mar 13 '09 at 14:14
Geo
45.3k89287465
45.3k89287465
add a comment |
add a comment |
4
Even if the question is duplicate, the answer in the other question is neither fast nor nice looking. It transforms the array into an arraylist (by hand).
– f1v3
Sep 22 '17 at 14:37