寻找从Java对象[]中删除元素的最佳方法

huangapple go评论105阅读模式
英文:

Looking for a optimal way to delete element from object[] java

问题

我有一个对象数组,我想根据其索引删除特定元素。我知道两种方法:

  1. 将对象[]转换为列表,然后使用remove函数。
  2. 将元素值设置为null,然后创建另一个对象数组并进行过滤。

是否有其他更优的方法来做这件事?

英文:

I have an object array from which I want to delete a specific element based on it's index. I know two ways for it:

  1. convert the object[] to a list and use remove function
  2. set the element value to null and then make another object array and
    filter it

Is there any other optimal way to do it?

答案1

得分: 2

  • 创建一个新的大小为 n-1 的数组。
  • 将旧数组中的元素从 0..index-1 复制到新数组中。
  • 将旧数组中的元素从 index+1..n 复制到新数组中。

对于数组复制操作,请使用 java.lang.System.arraycopy(Object, int, Object, int, int)

这可能是最优的方式。

英文:
  • Create a new array of size n-1.
  • Copy 0..index-1 elements from the old array to the new array.
  • Copy index+1..n elements from the old array to the new array.

Use java.lang.System.arraycopy(Object, int, Object, int, int) for array copy operations.

This would be probably the most optimal way.

答案2

得分: 0

另一种使用流的方法可能看起来像

Object[] myObject = {"foo", "bar", 42, 13, "doo"};
int indexToRemove = 3;

Object[] result = IntStream.range(0, myObject.length)
                            .filter(i -> i != indexToRemove)
                            .mapToObj(i -> myObject[i])
                            .toArray();
英文:

Another approach using streams could look like

Object[] myObject = {"foo", "bar", 42, 13, "doo"};
int indexToRemove = 3;
    
 Object[] result = IntStream.range(0, myObject.length)
                            .filter(i -> i != indexToRemove)
                            .mapToObj(i -> myObject[i])
                            .toArray();  

答案3

得分: -1

你应该使用迭代器来删除列表中的元素。
示例代码:

String[] array = {"one", "two", "three"};
List<String> list = new ArrayList<>(Arrays.asList(array));
Iterator<String> it = list.iterator();
int index = 0;
while (it.hasNext())
{
    String next = it.next();
    if (index == 1)
    {
        it.remove();
    }
    index++;
}
英文:

You should use Iterator to remove the element in list.
Example code:

String[] array = {&quot;one&quot;, &quot;two&quot;, &quot;three&quot;};
List&lt;String&gt; list = new ArrayList&lt;&gt;(Arrays.asList(array));
Iterator&lt;String&gt; it = list.iterator();
int index = 0;
while (it.hasNext())
{

    String next = it.next();
    if (index == 1)
    {
        it.remove();
    }

    index++;
}

huangapple
  • 本文由 发表于 2020年7月22日 17:40:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63031267.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定