簡體   English   中英

將特定索引處的數組值復制到另一個數組

[英]Copying values of array at specific indices to another array

我遇到了一種情況,我有一個數組,我需要復制一些特定的屬性(即特定indinces的值)而不是整個數組到另一個數組。

例如,如果初始數組是:

double[] initArray = {1.0, 2.0, 1.5, 5.0, 4.5};

那么如果我只想復制第2,第4和第5個屬性(即這些索引處的值),那么所需的輸出數組將是:

double[] reducedArray = {2.0, 5.0, 4.5};

我知道如果索引以順序形式出現,例如1-3,那么我可以使用System.arraycopy()但我的索引沒有那個方面。

那么,有沒有任何官方的方法來做到這一點,除了通過每個值的瑣碎循環並復制所需的:

double[] includedAttributes = {1, 4, 5};
double[] reducedArray = new double[includedAttributes.length];
for(int j = 0; j < includedAttributes.length; j++) {
    reducedArray[j] = initArray[includedAttributes[j]];
}

使用流,它是一個單行。

鑒於:

int[] indices;
double[] source;

然后:

double[] result = Arrays.stream(indices).mapToDouble(i -> source[i]).toArray();

簡單地說,除非你有特定的案例,否則它是不可能的。

例如:

您希望前N個項目具有最高值(在您的情況下為{2.0,4.5,5.0})

這樣做的快速(和骯臟)方式:

public static double[] topvalues(int n,double[] original){
 double[] output=new double[n];
 Arrays.sort(original);
 System.arraycopy(original,0,output,0,n);
 return output;
}

注意 :此方法也會對原始數組進行排序。 如果你不想要這種行為,可以使用不同的方法, 這里有一個列表:

以某種可能不受歡迎的方式回答你的問題,你可以為這種操作寫一個類:

public class PointerArray <T> {

    private T[] arr;
    private int[] indices;

    public PointerArray(T[] arr, int[] indices) {
        this.arr = arr;
        this.indices = indices;
    }

    public T get(int index) {
        return this.arr[this.indices[index]];
    }

    public void set(int index, T value) {
        this.arr[this.indices[index]] = value;
    }

    public int size() {
        return this.indices.length;
    }

}

這是未經測試的代碼,但這個想法至少應該通過。

使用它看起來像這樣:

int[] includedAttributes = {0, 3, 4};

PointerArray<Double> reducedArray =
    new PointerArray<Double>(initArray, includedAttributes);

for(int j = 0; j < reducedArray.size(); j++) {
    System.out.println(reducedArray.get(j));
}

我認為這是性能和內存方面的一個很好的解決方案,因為沒有任何東西被復制(也沒有被創建)。 唯一的缺點是需要調用get() ,但我不知道方法調用的確是多么昂貴。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM