0

This code generates unsorted array. My question is how do I clone the generated array so I can reuse the unsorted array in different sorting algorithms.

public class UnsortedData{

private int [] coreData;
private int maxArraySize;
private int currentArraySize;

public UnsortedData(int size){
    this.maxArraySize = size;
    this.coreData = new int[this.maxArraySize];
    this.currentArraySize = 0;
}

public boolean addData(int data){
    if (currentArraySize < maxArraySize)
    {
        coreData[currentArraySize] = data;
        currentArraySize++;
        return true;
    }
    return false;
}

public class dataSorting {

public static void main(String[] args) {
    Random rand = new Random();
    UnsortedData uD = new UnsortedData(1000000);

    for (int x = 0; x < 50; x++) {
        uD.addData(rand.nextInt(3000000));
    }

}
charlie
  • 11

2 Answers2

0

Use build in methods from java.lang.Object to clone the original array and java.util.Arrays to sort the cloned array.

int[] arr = {6,9,4,5};            // original array
int[] arrCopy = arr.clone()       // we created a copy of the array

Arrays.sort(arrCopy);             // it sort the array that we cloned

References: Arrays Class , Class Object

Eduard A
  • 370
  • 3
  • 9
0

Easiest way? Object.clone()

int[] arr = coreData.clone();

You can also use the Stream API or external libraries such as Apache Commons.

el-chico
  • 145
  • 1
  • 11
  • 2
    You need to see why [clone](https://stackoverflow.com/questions/2597965/why-people-are-so-afraid-of-using-clone-on-collection-and-jdk-classes) is not a good idea – Sync it Feb 11 '21 at 05:30