Paul D
Paul D

Reputation: 47

Way to create a copy of an array of vectors for further modification

I'm creating my own Vector class which is able to perform many different computations. However I seem to have come across an obstacle. I have a few methods such as sorting, scalar add/multiply and reversing methods which I need to perform, however I want to create a copy of the vector first so that I can modify it. This is my code of just the sorting method as an example:

    Vector vector = new Vector(length);

    for (int i = 0; i < length - 1; i++) {
        for (int j = i + 1; j < length; j++){
            if (vector.elements[i] > vector.elements[j]) {
                long temp = vector.elements[i];
                vector.elements[i] = vector.elements[j];
                vector.elements[j] = temp;
            }
        }
    }
    return vector;

In the above code, whenever I seem to run it, the output is always 0. However I know I need to create a clone of the vector input by the user and store it in the Vector "vector" object. How can I do this?

The instance variables I have are listed below:

public class Vector {

private Long sum;
private Long mode;
private Long median;
private Long minimum;
private Long maximum;

private final int length;
private final long[] elements;

public Vector(int length) {

    this.sum = null;
    this.mode = null;
    this.median = null;
    this.minimum = null;
    this.maximum = null;

    this.length = length;
    this.elements = new long[length];

Upvotes: 1

Views: 36

Answers (1)

Andy Turner
Andy Turner

Reputation: 140319

You just need a copy constructor, i.e. Vector(Vector other):

  • Assign all of the scalar fields using this.sum = other.sum; etc;
  • Assign the array fields using:

    this.elements = Arrays.copyOf(other.elements, other.elements.length);
    

(It's not clear why you need a length field, since elements.length == length - just use elements.length)

Upvotes: 2

Related Questions