如何在Java中从数组中删除对象?
给定一个n对象数组,假设它是一个字符串数组,它具有以下值:如何在Java中从数组中删除对象?,java,arrays,data-structures,data-manipulation,Java,Arrays,Data Structures,Data Manipulation,给定一个n对象数组,假设它是一个字符串数组,它具有以下值: foo[0] = "a"; foo[1] = "cc"; foo[2] = "a"; foo[3] = "dd"; 要删除/删除数组中等于“a”的所有字符串/对象,我必须做些什么?用数组.asList()从数组中创建一个列表,并在所有适当的元素上调用remove()。然后在“列表”上调用toArray(),再次返回数组 性能不太好,但如果您将其正确封装,以后总是可以做得更快。将null分配给数组位置。[如果您需要一些现成的代码,请滚动
foo[0] = "a";
foo[1] = "cc";
foo[2] = "a";
foo[3] = "dd";
要删除/删除数组中等于“a”的所有字符串/对象,我必须做些什么?用
数组.asList()
从数组中创建一个列表
,并在所有适当的元素上调用remove()
。然后在“列表”上调用toArray()
,再次返回数组
性能不太好,但如果您将其正确封装,以后总是可以做得更快。将null分配给数组位置。[如果您需要一些现成的代码,请滚动到我的“Edit3”(剪切后)。剩余的代码将留待以后使用。] 充实:
编辑3:如果在同一个类中频繁使用此代码,您可能希望考虑将此代码添加到类:
private static final String[] EMPTY_STRING_ARRAY = new String[0];
然后该函数变为:
List<String> list = new ArrayList<>();
Collections.addAll(list, array);
list.removeAll(Arrays.asList("a"));
array = list.toArray(EMPTY_STRING_ARRAY);
我更喜欢我的方法,因为显式大小可能更容易出错(例如,在错误的列表上调用
size()
。关于创建一个列表,然后删除,然后返回到数组的内容让我觉得是错的。还没有测试,但我认为下面的性能会更好。是的,我可能是过度地预优化了
boolean [] deleteItem = new boolean[arr.length];
int size=0;
for(int i=0;i<arr.length;i==){
if(arr[i].equals("a")){
deleteItem[i]=true;
}
else{
deleteItem[i]=false;
size++;
}
}
String[] newArr=new String[size];
int index=0;
for(int i=0;i<arr.length;i++){
if(!deleteItem[i]){
newArr[index++]=arr[i];
}
}
boolean[]deleteItem=new boolean[arr.length];
int size=0;
对于(int i=0;iArrgh),我无法正确显示代码。抱歉,我让它工作了。再次抱歉,我认为我没有正确阅读问题
String foo[] = {"a","cc","a","dd"},
remove = "a";
boolean gaps[] = new boolean[foo.length];
int newlength = 0;
for (int c = 0; c<foo.length; c++)
{
if (foo[c].equals(remove))
{
gaps[c] = true;
newlength++;
}
else
gaps[c] = false;
System.out.println(foo[c]);
}
String newString[] = new String[newlength];
System.out.println("");
for (int c1=0, c2=0; c1<foo.length; c1++)
{
if (!gaps[c1])
{
newString[c2] = foo[c1];
System.out.println(newString[c2]);
c2++;
}
}
String foo[]={“a”、“cc”、“a”、“dd”},
删除=“a”;
布尔间距[]=新布尔值[foo.length];
int newlength=0;
对于(int c=0;c编辑:
数组中带有空值的点已清除。很抱歉我的评论
原件:
嗯……电话线
array = list.toArray(array);
将已删除元素所在数组中的所有间隙替换为null。这可能是危险的,因为元素已删除,但数组的长度保持不变
如果要避免这种情况,请使用新数组作为toArray()的参数。如果不想使用removeAll,则可以使用集合:
String[] array = new String[] { "a", "bc" ,"dc" ,"a", "ef" };
System.out.println(Arrays.toString(array));
Set<String> asSet = new HashSet<String>(Arrays.asList(array));
asSet.remove("a");
array = asSet.toArray(new String[] {});
System.out.println(Arrays.toString(array));
其中,Chris Yester Young目前接受的答案是:
[a, bc, dc, a, ef]
[bc, dc, ef, null, ef]
使用代码
String[] array = new String[] { "a", "bc" ,"dc" ,"a", "ef" };
System.out.println(Arrays.toString(array));
List<String> list = new ArrayList<String>(Arrays.asList(array));
list.removeAll(Arrays.asList("a"));
array = list.toArray(array);
System.out.println(Arrays.toString(array));
String[]array=新字符串[]{“a”、“bc”、“dc”、“a”、“ef”};
System.out.println(array.toString(array));
List List=newarraylist(Arrays.asList(array));
list.removeAll(Arrays.asList(“a”));
array=list.toArray(数组);
System.out.println(array.toString(array));
没有留下任何空值。您始终可以执行以下操作:
int i, j;
for (i = j = 0; j < foo.length; ++j)
if (!"a".equals(foo[j])) foo[i++] = foo[j];
foo = Arrays.copyOf(foo, i);
inti,j;
对于(i=j=0;j
这取决于您所说的“删除”是什么意思?数组是一个固定大小的结构-您不能更改其中的元素数。因此,您可以a)创建一个新的、较短的数组,而不包含您不需要的元素,或者b)将您不需要的条目分配给指示其“空”状态的对象;如果不使用原语,则通常为null
在第一种情况下,从数组中创建一个列表,删除元素,然后从列表中创建一个新数组。如果性能很重要,则迭代数组,将不应删除的元素分配给列表,然后从列表中创建一个新数组。在第二种情况下,只需遍历并为数组项分配null。您可以使用外部库:
org.apache.commons.lang.ArrayUtils.remove(java.lang.Object[] array, int index)
这是在Apache Commons Lang项目中,我意识到这是一篇非常古老的帖子,但是这里的一些答案帮助了我,所以这是我的一便士的价值
我花了很长时间才让它正常工作,直到我发现我要写回的数组需要调整大小,除非对ArrayList
所做的更改保持列表大小不变
如果您正在修改的ArrayList
的元素比开始时多或少,则行List.toArray()
将导致异常,因此您需要类似于List.toArray(新字符串[]{})
或List.toArray(新字符串[0])
的内容,以便使用新的(正确)字符串创建数组尺寸
现在我知道了,听起来很明显。对于一个熟悉新的和不熟悉的代码结构的Android/Java新手来说,这一点并不明显,在这里的一些早期文章中,这一点也不明显,所以我只想让其他人明白这一点,就像我一样,挠头好几个小时 我对这个问题的贡献很小
public class DeleteElementFromArray {
public static String foo[] = {"a","cc","a","dd"};
public static String search = "a";
public static void main(String[] args) {
long stop = 0;
long time = 0;
long start = 0;
System.out.println("Searched value in Array is: "+search);
System.out.println("foo length before is: "+foo.length);
for(int i=0;i<foo.length;i++){ System.out.println("foo["+i+"] = "+foo[i]);}
System.out.println("==============================================================");
start = System.nanoTime();
foo = removeElementfromArray(search, foo);
stop = System.nanoTime();
time = stop - start;
System.out.println("Equal search took in nano seconds = "+time);
System.out.println("==========================================================");
for(int i=0;i<foo.length;i++){ System.out.println("foo["+i+"] = "+foo[i]);}
}
public static String[] removeElementfromArray( String toSearchfor, String arr[] ){
int i = 0;
int t = 0;
String tmp1[] = new String[arr.length];
for(;i<arr.length;i++){
if(arr[i] == toSearchfor){
i++;
}
tmp1[t] = arr[i];
t++;
}
String tmp2[] = new String[arr.length-t];
System.arraycopy(tmp1, 0, tmp2, 0, tmp2.length);
arr = tmp2; tmp1 = null; tmp2 = null;
return arr;
}
公共类DeleteElementFromArray{
公共静态字符串foo[]={“a”、“cc”、“a”、“dd”};
公共静态字符串搜索=“a”;
公共静态void main(字符串[]args){
长停止=0;
长时间=0;
长启动=0;
System.out.println(“数组中的搜索值为:“+search”);
System.out.println(“之前的foo长度为:“+foo.length”);
对于(int i=0;i参见下面的代码
ArrayList<String> a = new ArrayList<>(Arrays.asList(strings));
a.remove(i);
strings = new String[a.size()];
a.toArray(strings);
ArrayList a=新的ArrayList(Arrays.asList(strings));
a、 删除(i);
字符串=新字符串[a.size()];
a、 toArray(字符串);
Java 8中的替代方案:
String[] filteredArray = Arrays.stream(array)
.filter(e -> !e.equals(foo)).toArray(String[]::new);
如果需要从数组中删除多个元素而不将其转换为列表
或创建其他数组,则可以在O(n)中执行此操作,而不依赖于要删除的项目数
这里,a
是初始数组,int…r
是要删除的元素的不同有序索引(位置):
public int removeItems(Object[] a, int... r) {
int shift = 0;
for (int i = 0; i < a.length; i++) {
if (shift < r.length && i == r[shift]) // i-th item needs to be removed
shift++; // increment `shift`
else
a[i - shift] = a[i]; // move i-th item `shift` positions left
}
for (int i = a.length - shift; i < a.length; i++)
a[i] = null; // replace remaining items by nulls
return a.length - shift; // return new "length"
}
在您的任务中,您可以首先扫描数组以收集“a”的位置,然后调用removietems()
将复制除索引为i的元素之外的所有元素:
if(i == 0){
System.arraycopy(edges, 1, copyEdge, 0, edges.length -1 );
}else{
System.arraycopy(edges, 0, copyEdge, 0, i );
System.arraycopy(edges, i+1, copyEdge, i, edges.length - (i+1) );
}
这里有很多答案——我看到的问题是,您没有说明为什么要使用数组而不是集合,所以让我提出几个原因,以及应该应用哪些解决方案(大多数解决方案已经在其他问题中得到了回答,所以我
ArrayList<String> a = new ArrayList<>(Arrays.asList(strings));
a.remove(i);
strings = new String[a.size()];
a.toArray(strings);
String[] filteredArray = Arrays.stream(array)
.filter(e -> !e.equals(foo)).toArray(String[]::new);
public int removeItems(Object[] a, int... r) {
int shift = 0;
for (int i = 0; i < a.length; i++) {
if (shift < r.length && i == r[shift]) // i-th item needs to be removed
shift++; // increment `shift`
else
a[i - shift] = a[i]; // move i-th item `shift` positions left
}
for (int i = a.length - shift; i < a.length; i++)
a[i] = null; // replace remaining items by nulls
return a.length - shift; // return new "length"
}
String[] a = {"0", "1", "2", "3", "4"};
removeItems(a, 0, 3, 4); // remove 0-th, 3-rd and 4-th items
System.out.println(Arrays.asList(a)); // [1, 2, null, null, null]
if(i == 0){
System.arraycopy(edges, 1, copyEdge, 0, edges.length -1 );
}else{
System.arraycopy(edges, 0, copyEdge, 0, i );
System.arraycopy(edges, i+1, copyEdge, i, edges.length - (i+1) );
}
System.arraycopy(ary, n+1, ary, n, length-n)
length--;
int[] array = {5,6,51,4,3,2};
for(int i = 2; i < array.length -1; i++){
array[i] = array[i + 1];
}
class clearname{
def parts
def tv
public def str = ''
String name
clearname(String name){
this.name = name
this.parts = this.name.split(" ")
this.tv = this.parts.size()
}
public String cleared(){
int i
int k
int j=0
for(i=0;i<tv;i++){
for(k=0;k<tv;k++){
if(this.parts[k] == this.parts[i] && k!=i){
this.parts[k] = '';
j++
}
}
}
def str = ''
for(i=0;i<tv;i++){
if(this.parts[i]!='')
this.str += this.parts[i].trim()+' '
}
return this.str
}}
return new clearname(name).cleared()
boolean[] done = {false};
String[] arr = Arrays.stream( foo ).filter( e ->
! (! done[0] && Objects.equals( e, item ) && (done[0] = true) ))
.toArray(String[]::new);