[英]How to trim out an array of integers in Java?
假設我有一個數字 N。 N 將是數組的大小。
int numArray [] = new numArray[N];
但是,數組的內容將保存從 1 到正 N 的每隔一個數字。這意味着在 for 循環之后整個大小為 N 的數組將不會被填滿。 所以在 for 循環之后,我想修剪(或調整大小)數組,以便數組中不再有任何空槽。
例子 :
假設 N = 5; 這意味着,在 for 循環之后,從 1 到 5 的每個其他數字都將在數組中,如下所示:
int arr[] = new int[N];
int arr[0]=1;
int arr[1]=3;
int arr[2]= null;
int arr[3]= null;
int arr[4]= null;
現在,我想在 for 循環之后修剪(或調整大小),以便保持 null 的索引將消失,然后數組應該是:
int arr[0]=1;
int arr[1]=3;
數組的大小現在是 2。
您不能修剪數組。 最快的方法是使用 System.arraycopy 將其復制到較小的文件中,這幾乎總是比 for 循環快得多:
int somesize = 5;
int[] numArray = new int[somesize];
//code to populate every other int into the array.
int[] smallerArray = new int[somesize/2];
//copy array into smaller version
System.arraycopy(numArray, 0, smallerArray, 0, somesize / 2);
在 Java 中創建數組后,您無法更改它的大小。 但是,您可以做的是創建一個您需要的大小的新數組。
另一個重要的點是您正在創建一個原始數組: int
。 基元不是對象,您不能將值null
分配給基元。 如果您希望能夠將其中的條目設置為null
,則需要創建一個java.lang.Integer
數組。
Integer[] numArray = new Integer[N];
得益於稱為auto-boxing的 Java 功能,幾乎所有使用原始int
值的代碼也適用於Integer
值。
腳步:
Integer[]
而不是int[]
null
條目)null
值復制到新數組中。代碼:
Integer[] oldArray = ...;
// Step 2
int count = 0;
for (Integer i : oldArray) {
if (i != null) {
count++;
}
}
// Step 3
Integer[] newArray = new Integer[count];
// Step 4
int index = 0;
for (Integer i : oldArray) {
if (i != null) {
newArray[index++] = i;
}
}
我認為有一種更短的方法來進行修剪本身。 剩下的就是找到合適的索引。
你可以做:
int someIndex = Arrays.asList(arr).indexOf(null);
arr = Arrays.copyOfRange(arr,0,someIndex);
你肯定會更好地使用一些更合適的數據結構,例如一個列表或一個集合,這取決於你以后的意圖。 這樣你甚至不需要創建一個 N 大小的結構,所以你無論如何都必須減少它。 而是創建一個空列表並添加您實際需要的元素
import java.util.Arrays;
public static void main( String[] args )
{
int[] nums2 = {9,4,1,8,4};
nums2 =Arrays.copyOf(nums2,3);
for (int i : nums2) {
System.out.print(i+" ");
}
}
//輸出
9 4 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.