1

I am having problem. At my main class, I have:

int  ints[] = Type.desc(1000);
int  auxi[] = new int [1000];
auxi = ints;

System.out.println("========== Init =========");
// Insertion Sort
Algoritmos.insertionSort(ints);
ints = auxi;

The desc method is:

public static int[] desc (int n){
    int aux[];
    aux = new int[n];
    int pos = 0;
    for (int i = n-1; i > 0; i--) {
        aux[pos++] = i;
    }

    return aux;
}

The the value of ints and auxi are changed.

How can I save the initial value of the vector ints?

4 Answers 4

3

How can I save the initial valeu of the vector ints?

Make a copy of the array, like this:

int[] copy = new int[orig.length];
System.arraycopy(orig, 0, copy, 0, orig.length);

Note that this makes a shallow copy of the array. It does not matter for primitives, but for reference types you may need to make more work to make a copy.

Sign up to request clarification or add additional context in comments.

2 Comments

@RenatoShumi Not really, no: you can also use clone() and cast to int[], or Arrays.copyOf().
As long as you use don't more advanced data structures like ArrayList... Yes... (other than what EJP mentioned, i.e. looping by yourself or copyOf(), I mean).
2
int  ints[] = Type.desc(1000);
int  auxi[] = new int [1000];
auxi = ints;

How can I save the initial valeu of the vector ints?

Don't assign it to another variable. The initialization in your second line above is pointless, as you then proceed to assign ints to auxi. This step doesn't copy the array, it just copies the reference. If you want to keep the original array, change the third line to a loop that copies the elements, or use Arrays.copyOf() or System.arraycopy().

Comments

1

instead of doing this

auxi = ints;

use

System.arrayCopy()

Comments

0

You could use

int [] original_array_backup = new int [ints.length]
System.arraycopy(ints, 0, original_array_backup, 0)

So you could pass original_array_backup into your algorithm without losing the data and order of your ints array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.