java中刪除 數(shù)組中的指定元素要如何來實現(xiàn)呢,如果各位對于這個算法不是很清楚可以和小編一起來看一篇關于java中刪除 數(shù)組中的指定元素的例子。
java的api中,并沒有提供刪除數(shù)組中元素的方法。雖然數(shù)組是一個對象,不過并沒有提供add()、remove()或查找元素的方法。這就是為什么類似ArrayList和HashSet受歡迎的原因。
不過,我們要感謝Apache Commons Utils,我們可以使用這個庫的ArrayUtils類來輕易的刪除數(shù)組中的元素。不過有一點需要注意,數(shù)組是在大小是固定的,這意味這我們刪除元素后,并不會減少數(shù)組的大小。
所以,我們只能創(chuàng)建一個新的數(shù)組,然后使用System.arrayCopy()方法將剩下的元素拷貝到新的數(shù)組中。對于對象數(shù)組,我們還可以將數(shù)組轉(zhuǎn)化為List,然后使用List提供的方法來刪除對象,然后再將List轉(zhuǎn)換為數(shù)組。
為了避免麻煩,我們使用第二種方法:
我們使用Apache commons庫中的ArrayUtils類根據(jù)索引來刪除我們指定的元素。
Apache commons lang3下載地址:
http://commons.apache.org/proper/commons-lang/download_lang.cgi
下載好后,導入jar。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
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 ] |
當然,我們還有其他的方法,不過使用已經(jīng)的庫或java api來實現(xiàn),更快速。
我們來看下ArrayUtils.remove(int[] array, int index)
方法源代碼:
1
2
3
|
public static int [] remove( int [] array, int index) { return ( int [])(( int [])remove((Object)array, index)); } |
在跳轉(zhuǎn)到remove((Object)array, index)) ,源代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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的刪除數(shù)組中元素的原理了吧。其實還是要用到兩個數(shù)組,然后利用System.arraycopy()方法,將除了要刪除的元素外的其他元素都拷貝到新的數(shù)組中,然后返回這個新的數(shù)組。
以上就是小編為大家?guī)淼膉ava中刪除 數(shù)組中的指定元素方法全部內(nèi)容了,希望大家多多支持服務器之家~