Comparing Arrays - Java Language Basics

Java examples for Language Basics:Array

Description

Comparing Arrays

Demo Code

import java.util.Arrays;

public class Main {

  public static void main(String[] argv) {
    // null arrays are equal
    boolean[] bArr1 = null;
    boolean[] bArr2 = null;
    boolean b = Arrays.equals(bArr1, bArr2);

    // Compare two boolean arrays
    bArr1 = new boolean[] { true, false };
    bArr2 = new boolean[] { true, false };
    b = Arrays.equals(bArr1, null); 
    b = Arrays.equals(bArr1, bArr2); 

    // There are equals() methods for all eight primitive types
    b = Arrays.equals(new byte[] { 0 }, new byte[] { 0 }); 
    b = Arrays.equals(new char[] { 'a' }, new char[] { 'a' }); 
    b = Arrays.equals(new short[] { 0 }, new short[] { 0 }); 
    b = Arrays.equals(new int[] { 0 }, new int[] { 0 }); 
    b = Arrays.equals(new long[] { 0L }, new long[] { 0L }); 
    b = Arrays.equals(new float[] { 0F }, new float[] { 0F }); 
    b = Arrays.equals(new double[] { 0D }, new double[] { 0D }); 

    // When comparing Object arrays, null elements are equal.
    // If the elements are not null, Object.equals() is used.
    b = Arrays.equals(new String[] { "a" }, new String[] { "a" }); 
    b = Arrays.equals(new String[] { null }, new String[] { null }); 
    b = Arrays.equals(new String[] { "a" }, new String[] { null }); 
  }//w w w  .j  a v a  2 s . c  o m
}

Related Tutorials