Bolton
Bolton

Reputation: 2256

Determine if part of two arrays equal in java

I have two char arrays of different length, and I want to compare whether the first few chars in both arrays are the same. e.g.

char[] pngheader = new char[] { 137, 80, 78, 71 }; // PNG
char[] fileheader = new char[] { 137, 80, 78, 71 , xxx, xxx}; 

I am wondering whether if I could do this using some elegant way like Arrays.equals()?
Thanks in advance.

Upvotes: 0

Views: 111

Answers (2)

Kevin Bowersox
Kevin Bowersox

Reputation: 94459

The Arrays class provides some helpful methods for your situation.

public static void main(String[] args) {
    char[] pngheader = new char[] { 137, 80, 78, 71 }; // PNG
    char[] fileheader = new char[] { 137, 80, 78, 71 , 1, 2}; 
    char[] fileheader2 = new char[] { 131, 80, 78, 71 , 1, 2}; 

    boolean equals = Arrays.equals(Arrays.copyOf(pngheader, 4),
                                        Arrays.copyOf(fileheader, 4));
    System.out.println(equals); //prints true

    boolean equals2 = Arrays.equals(Arrays.copyOf(pngheader, 4),
                                       Arrays.copyOf(fileheader2, 4));
    System.out.println(equals2); //prints false
}

This could also be made more reusable by creating a method.

    public static boolean arraysEquals(char[] arr1, char[] arr2, int length){
        return Arrays.equals(Arrays.copyOf(arr1, length -1), 
                        Arrays.copyOf(arr2, length -1));
    }

    //Usage

    arraysEquals(pngheader, fileheader, 4);
    arraysEquals(pngheader, fileheader2, 4);

Upvotes: 3

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136012

This will work with char arrays

    char[] pngheader = new char[] { 137, 80, 78, 71 }; // PNG
    char[] fileheader = new char[] { 137, 80, 78, 71 , 1, 1}; 
    boolean res = new String(fileheader).startsWith(new String(pngheader));
    System.out.println(res);

Upvotes: 1

Related Questions