4

我真的希望Processing 有用于处理数组的pushpop方法,但由于它没有,我只能试图找出在数组中的特定位置删除对象的最佳方法。我确信这对许多人来说是最基本的,但我可以使用一些帮助,而且我无法通过浏览处理参考来弄清楚。

我认为这并不重要,但供您参考的是我最初用于添加对象的代码:

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 移除一个对象。谢谢,伙计们。

4

5 回答 5

6

您可能还想考虑使用ArrayList,它比普通数组有更多可用的方法。

您可以使用删除第十五个元素myArrayList.remove(14)

于 2010-04-29T23:07:52.670 回答
1

我做了一个函数,它基本上将要删除的索引切换到最后一个,然后缩短它。

int[] removeByIndex(int[] array, int index) {
  int index2 = array.length-1;
  int old = array[index];
  array[index] = array[index2];
  array[index2] = old;
  array = shorten(array);
  return array;
}

yourarray = removeByIndex(yourarray , arrayindex);

希望这可以帮助!

于 2019-10-19T16:11:11.430 回答
0

我认为你最好的选择是使用arraycopy。您可以对 src 和 dest 使用相同的数组。类似于以下内容(未经测试):

// move the end elements down 1
arraycopy(flowers, 16, flowers, 15, flowers.length-16);
// remove the extra copy of the last element
flowers = shorten(flowers);
于 2010-03-17T15:12:32.973 回答
0
String[] myArray = { "0", "1", "2", "3", "4", "5", "6"}; 

String[] RemoveItem(String[] arr, int n) {
  if (n < arr.length-1) {
    arrayCopy(subset(arr, n+1), 0, arr, n, arr.length-1-n);
  }
  arr = shorten(arr);
  return arr;
}
于 2021-05-04T20:48:40.693 回答
-1

我知道这个问题很久以前就被问过了,但似乎很多人仍在寻找答案。我刚写了这个。我测试了几种方法,它似乎按照我想要的方式运行。

var yourArr = [1, 2, 3, 4];                                // use your array here
var removeIndex = 1;                                       // item to get rid of 

var explode = function(array, index) {                     // create the function
    var frontSet = subset(array, 0, index - 1);            // get the front
    var endSet = subset(array, index , array.length - 1);  // get the end
    yourArr = concat(frontSet, endSet);                    // join them
};

explode(yourArr, removeIndex);                             // call it on your array

这是一种方式。我想你也可以遍历数组。就像是 ...

var yourArr = [1, 2, 3, 4];
var removeIndex = 2;
var newArr = [];

for(var i = 0; i < yourArr.length; i++) {
    if(i < removeIndex) {
        append(newArr, yourArr[i]);
    } else if(i > removeIndex) {
        append(newArr, yourArr[i]);
    }
}

yourArr = newArr;

...认为这也应该有效。希望这可以帮助任何需要它的人。

于 2016-12-23T08:28:54.677 回答