0

I was trying to reverse the order of an array and print it. I did this by moving each element into an ArrayList using a for loop decremented from the (array.length-1). Then I tried to use the 'arrayList.toArray(array)'method. I know it returns 'object [ ]' so i changed my 'int [ ]' to 'Integer [ ]' and it worked.

My question is what is the difference between an array 'Integer []' and 'int [ ]'

public static void main(String[] args) {
    //here i changed int [] to Integer []
    Integer[] arr ={ 4,3,5,7,8,2,9,1};
    System.out.println("array list \t :"+ Arrays.toString(arr)+"\n");
    System.out.println(" pos 1:   " + arr[1]);
    System.out.println("pos last: " + arr[arr.length-1]);
    System.out.println("*********************************");
    swapElements(arr);
    System.out.println("array list after  :"+ Arrays.toString(arr)+"\n");
    System.out.println("pos 1 after swap is:\t" + arr[1]);
    System.out.println("pos last after swap is: " + arr[arr.length-1]);

}
public static void  swapElements(Integer []array)
{ 
    ArrayList<Integer> array2 = new ArrayList<Integer>();
    for(int i =array.length -1;i>=0; i--)
    {

        array2.add(array[i]);

    }
    array2.toArray(array);
}
Crazypigs
  • 87
  • 3
  • 13

1 Answers1

1

Elements of int[] are by defualt initialized with value of 0, but the elements of Integer[] are by default initialized to null.

In some cases, you might need nulls (to denote nothing) instead of 0s.

brso05
  • 13,142
  • 2
  • 21
  • 40
Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142