在处理中从数组中删除对象的最佳方法
我真的希望处理有 push 和 pop 方法来处理数组,但由于它没有,所以我只能尝试找出在某个位置删除对象的最佳方法。数组中的特定位置。我确信这对很多人来说都是最基本的,但我可以使用一些帮助,并且通过浏览处理参考我还没有弄清楚太多。
我认为这并不重要,但供您参考的是我最初用于添加对象的代码:
Flower[] flowers = new Flower[0];
for (int i=0; i < 20; i++)
{
Flower fl = new Flower();
flowers = (Flower[]) expand(flowers, flowers.length + 1);
flowers[flowers.length - 1] = fl;
}
为了解决这个问题,我们假设我想从位置 15 删除一个对象。谢谢,伙计们。
I really wish Processing had push and pop methods for working with Arrays, but since it does not I'm left trying to figure out the best way to remove an object at a specific position in an array. I'm sure this is as basic as it gets for many people, but I could use some help with it, and I haven't been able to figure much out by browsing the Processing reference.
I don't think it matters, but for your reference here is the code I used to add the objects initially:
Flower[] flowers = new Flower[0];
for (int i=0; i < 20; i++)
{
Flower fl = new Flower();
flowers = (Flower[]) expand(flowers, flowers.length + 1);
flowers[flowers.length - 1] = fl;
}
For the sake of this question, let's assume I want to remove an object from position 15. Thanks, guys.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可能还需要考虑使用 ArrayList ,它比普通数组有更多可用的方法。
您可以使用
myArrayList.remove(14)
删除第十五个元素You may also want to consider using ArrayList which has more methods available than a plain array.
You can remove the fifteenth element by using
myArrayList.remove(14)
我做了一个函数,基本上将要删除的索引切换到最后一个,然后缩短它。
希望这有帮助!
I made a funtion which basically switches the index to be removed to the last and then shortens it.
hope this helps!
我认为你最好的选择是使用 arraycopy。您可以对 src 和 dest 使用相同的数组。类似于以下内容(未经测试):
I think that your best bet is to use arraycopy. You can use the same array for src and dest. Something like the following (untested):
我知道这个问题很久以前就被问过,但似乎很多人仍在寻找答案。我刚刚写了这个。我测试了几种方法,它似乎按照我想要的方式运行。
这是一种方法。我想你也可以循环遍历数组。像……
这样的东西也应该有效。希望这可以帮助任何有需要的人。
I know this question was asked a long time ago however it seems a lot of people are still looking for the answer. I just wrote this. I tested it a few ways and it seems to run the way I wanted it to.
That is one way. I guess you could loop through the array as well. Something like ...
... think that should work too. Hope this helps anybody who needs it.