繁体   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