Object-Oriented Programming with Java, part I – Exercise 98

This exercise creates a copy of an integer array in one method and then reverses it in another.

My Code

Main

import java.util.Arrays;

public class Main {

public static void main(String[] args) {
    int[] original = {1, 2, 3, 4};
    int[] reverse = reverseCopy(original);

    // print both
    System.out.println( "original: " +Arrays.toString(original));
    System.out.println( "reversed: " +Arrays.toString(reverse));
}

public static int[] copy(int[] array){
    int[] copied = array.clone();
    return copied;
}

public static int[] reverseCopy(int[] array){
    int[] reversed = array.clone();
    int i = 0;
    for (int l = (array.length - 1) ; l >= 0; l--){
    reversed[i] = array[l];
    i++;
}
    return reversed;
}
}

Model Code

Main

import java.util.Arrays;

 

public class Main {

 

    public static void main(String[] args) {

        // write testcode here

        int[] original = {1, 2, 3, 4};

        int[] copied = copy(original);

        

        // change the copy

        copied[0] = 99;

        

        // printing both

        System.out.println( "original: " +Arrays.toString(original));

        System.out.println( "copied: " +Arrays.toString(copied));               

        

        System.out.println("");

        

        int[] reversed = reverseCopy(original);

        

        // printing both

        System.out.println( "original: " +Arrays.toString(original));

        System.out.println( "reversed: " +Arrays.toString(reversed));        

    }

    

    public static int[] copy(int[] array){

        int[] copy = new int[array.length];

        

        for (int i = 0; i < copy.length; i++) {

            copy[i] = array[i];            

        }

        

        return copy;

    }

    

    public static int[] reverseCopy(int[] array){

        int[] reversed = new int[array.length];

        

        for (int i = 0; i < reversed.length; i++) {

            reversed[i] = array[array.length-1-i];            

        }

        

        return reversed;

    }    

}

Comments

For the first method I prefer my solution which is to clone the array. In the second I prefer their solution. It does seem slightly simpler.

Leave a comment