简体   繁体   中英

Merging a new object in java with an already existing one

I want to know how can i merge two objects in java. I've tried creating a 3rd class but to no avail. The first one being the this object and the next one is given through the method. Something like:

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();
    }


}

In your merge method, you need to create a new int[] , one whose length is the size of the this.a.length + the other object's length, use for loops to place the this.a values into the new array, and then another for-loop to place the merging object's array's values in. Note that you must be careful to use the correct indices for the new array when adding inthe 2nd array -- you must add the first int array's length to the index when referencing the new array item. Then create a new IntegerArray object with this newly created longer array.

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);
}

In the contact() method, you need to create an array whose length is equal to the sum of the lengths of the this.a and ia, arrays then copy the this.a array into that new array and also copy the contents of ia into it. Then you can create a new IntegerArray passing that new array as the argument to the constructor.

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

Aah - @DontKnowMuchBut beat me by a few seconds

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM