簡體   English   中英

將java中的一個新對象與一個已經存在的對象合並

[英]Merging a new object in java with an already existing one

我想知道如何在 Java 中合並兩個對象。 我試過創建第三堂課,但無濟於事。 第一個是this對象,下一個是通過方法給出的。 就像是:

import java.util.Arrays;

public final class IntegerArray {
    private int[] a;

    public IntegerArray(int[] a) {
        this.a = a;
    }

    public int length() {
        return a.length;
    }

    public int getElementAt(int i) {
        return a[i];
    }

    public int sum() {
        int sum = 0;
        for(int i: a) {
            sum += i;
        }
        return sum;
    }

    public double average() {
        int i, sum = 0, armean;
        for(i = 0; i < a.length; i++) {
            sum = sum + a[i];
        }
        armean = sum / i;
        return armean;
    }

    public IntegerArray getSorted() {
        int[] b = a.clone();
        Arrays.sort(b);
        return new IntegerArray(b);
    }

    public IntegerArray contact(IntegerArray ia) {
        IntegerArray merged  = new IntegerArray(this.a);
    }

    @Override
    public String toString() {
        return a.toString();
    }


}

在您的合並方法中,您需要創建一個新的int[] ,其長度是this.a.length的大小 + 另一個對象的長度,使用 for 循環將this.a值放入新數組中,並且然后是另一個 for 循環來放置合並對象的數組的值。請注意,在添加到第二個數組時,必須小心為新數組使用正確的索引——引用時必須將第一個 int 數組的長度添加到索引中新的數組項。 然后用這個新創建的更長的數組創建一個新的 IntegerArray 對象。

public IntegerArray merge(IntegerArray other) {
    int[] newA = new int[a.length + other.a.length];
    for (int i = 0; i < a.length; i++) {
        newA[i] = a[i];
    }
    for (int i = 0; i < other.a.length; i++) {
        // here is where you need to be careful about the index
        newA[i + a.length] = other.a[i];
    }
    return new IntegerArray(newA);
}

在contact()方法中,你需要創建一個數組,它的長度等於this.a和ia的長度之和,數組然后將this.a數組復制到那個新數組中,同時復制ia的內容進去。 然后,您可以創建一個新的 IntegerArray,將該新數組作為參數傳遞給構造函數。

  int temp[] = new int[sum_of_lengths];
  // copy this.a elements into temp
  // copy ia elements into temp
  IntegerArray merged = new IntegerArray(temp);

啊 - @DontKnowMuchBut 擊敗了我幾秒鍾

暫無
暫無

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

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