// This class is a test program for showing that arrays are like objects.

 

// command: javac IntArrayTest4.java

// command: java IntArrayTest4

 

import java.util.Arrays;

 

public class IntArrayTest4 {

      

   // main( )

       public static void main (String args[] ) {

             int [] ar1 = new int [10];

             int [] ar2 = new int [10];

 

             // ar1 and ar2 contain the same values

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

                    ar1[i] = 2*i + i - 20;

             }

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

                    ar2[i] = 2*i + i - 20;

             }

 

             // Two arrays of the same values are not equal.

             if (ar1 == ar2)

                    System.out.println ("The two arrays are the same.");

             else

                    System.out.println ("The two arrays are not the same.");

 

             if ( ar1.equals(ar2) ) // compared as two objects

                    System.out.println ("The two arrays are the same.");

             else

                    System.out.println ("The two arrays are not the same.");

 

             if ( Arrays.equals(ar1, ar2) ) // comparison for array contents

                    System.out.println ("The two arrays have the same values.");

             else

                    System.out.println ("The two arrays have different values.");

 

             System.out.println ("Before assignment ...");

             System.out.println ("ar1[3] = " + ar1[3] + "\t\tar2[3] = " + ar2[3]);

 

             ar1=ar2;

             // Assigning ar2 to ar1 makes them reference the same object.

             if (ar1 == ar2)

                    System.out.println ("The two arrays are the same.");

             else

                    System.out.println ("The two arrays are not the same.");

 

             if ( ar1.equals(ar2) ) // compared as two objects

                    System.out.println ("The two arrays are the same.");

             else

                    System.out.println ("The two arrays are not the same.");

 

             if ( Arrays.equals(ar1, ar2) ) // comparison for array contents

                    System.out.println ("The two arrays have the same values.");

             else

                    System.out.println ("The two arrays have different values.");

 

             System.out.println ("After assignment (before set) ...");

             System.out.println ("ar1[3] = " + ar1[3] + "\t\tar2[3] = " + ar2[3]);

 

             ar2[3] = 33333; //Changing ar2[3] will also change ar1[3]

             System.out.println ("After set ...");

             System.out.println ("ar1[3] = " + ar1[3] + "\t\tar2[3] = " + ar2[3]);

       } //main()

 

} // IntArrayTest2 class