当前位置: 移动技术网 > IT编程>开发语言>Java > java中删除 数组中的指定元素方法

java中删除 数组中的指定元素方法

2019年07月22日  | 移动技术网IT编程  | 我要评论

java中删除 数组中的指定元素要如何来实现呢,如果各位对于这个算法不是很清楚可以和小编一起来看一篇关于java中删除 数组中的指定元素的例子。

java的api中,并没有提供删除数组中元素的方法。虽然数组是一个对象,不过并没有提供add()、remove()或查找元素的方法。这就是为什么类似arraylist和hashset受欢迎的原因。

不过,我们要感谢apache commons utils,我们可以使用这个库的arrayutils类来轻易的删除数组中的元素。不过有一点需要注意,数组是在大小是固定的,这意味这我们删除元素后,并不会减少数组的大小。

所以,我们只能创建一个新的数组,然后使用system.arraycopy()方法将剩下的元素拷贝到新的数组中。对于对象数组,我们还可以将数组转化为list,然后使用list提供的方法来删除对象,然后再将list转换为数组。

为了避免麻烦,我们使用第二种方法:

我们使用apache commons库中的arrayutils类根据索引来删除我们指定的元素。

apache commons lang3下载地址:
http://commons.apache.org/proper/commons-lang/download_lang.cgi

下载好后,导入jar。

import java.util.arrays;
import org.apache.commons.lang3.arrayutils;
/**
 *
 * java program to show how to remove element from array in java
 * this program shows how to use apache commons arrayutils to delete
 * elements from primitive array.
 *
 */
public class removeobjectfromarray{
  public static void main(string args[]) {
         
    //let's create an array for demonstration purpose
    int[] test = new int[] { 101, 102, 103, 104, 105};
   
    system.out.println("original array : size : " test.length );
    system.out.println("contents : " arrays.tostring(test));
   
    //let's remove or delete an element from array using apache commons arrayutils
    test = arrayutils.remove(test, 2); //removing element at index 2
   
    //size of array must be 1 less than original array after deleting an element
    system.out.println("size of array after removing an element : " test.length);
    system.out.println("content of array after removing an object : "
              arrays.tostring(test));
   
  }
 
}
output:
original array : size : 5
contents : [101, 102, 103, 104, 105]
size of array after removing an element : 4
content of array after removing an object : [101, 102, 104, 105]

当然,我们还有其他的方法,不过使用已经的库或java api来实现,更快速。

我们来看下arrayutils.remove(int[] array, int index)

方法源代码:

 public static int[] remove(int[] array, int index) {
    return (int[])((int[])remove((object)array, index));
  }

在跳转到remove((object)array, index)) ,源代码:

private static object remove(object array, int index) {
    int length = getlength(array);
    if(index >= 0 && index < length) {
      object result = array.newinstance(array.getclass().getcomponenttype(), length - 1);
      system.arraycopy(array, 0, result, 0, index);
      if(index < length - 1) {
        system.arraycopy(array, index 1, result, index, length - index - 1);
      }
      return result;
    } else {
      throw new indexoutofboundsexception("index: " index ", length: " length);
    }
  }

这下明白了arrayutils的删除数组中元素的原理了吧。其实还是要用到两个数组,然后利用system.arraycopy()方法,将除了要删除的元素外的其他元素都拷贝到新的数组中,然后返回这个新的数组。

以上就是小编为大家带来的java中删除 数组中的指定元素方法全部内容了,希望大家多多支持移动技术网~

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网