英文:
Looking for a optimal way to delete element from object[] java
问题
我有一个对象数组,我想根据其索引删除特定元素。我知道两种方法:
- 将对象[]转换为列表,然后使用remove函数。
- 将元素值设置为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:
- convert the object[] to a list and use remove function
- 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 = {"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++;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论