Determine if part of two arrays equal in java -
i have 2 char arrays of different length, , want compare whether first few chars in both arrays same. e.g.
char[] pngheader = new char[] { 137, 80, 78, 71 }; // png char[] fileheader = new char[] { 137, 80, 78, 71 , xxx, xxx}; i wondering whether if using elegant way arrays.equals()?
in advance.
the arrays class provides helpful methods 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 made more reusable creating 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);
Comments
Post a Comment