are two char array Equivalent - Java Collection Framework

Java examples for Collection Framework:Array Element

Description

are two char array Equivalent

Demo Code


//package com.java2s;
import java.util.ArrayList;

import java.util.List;

public class Main {
    public static void main(String[] argv) throws Exception {
        char[] charArr1 = new char[] { 'b', 'o', 'o', 'k', '2', 's', '.',
                'c', 'o', 'm', 'a', '1', };
        char[] charArr2 = new char[] { 'b', 'o', 'o', 'k', '2', 's', '.',
                'c', 'o', 'm', 'a', '1', };
        System.out.println(isEquivalent(charArr1, charArr2));
    }//from  ww w. j  a  v  a2 s  . com

    public static boolean isEquivalent(char[] charArr1, char[] charArr2) {
        if (charArr1.length != charArr2.length) {
            return false;
        }
        int sum1 = 0;
        int sum2 = 0;
        for (int index = 0; index < charArr1.length; index++) {
            sum1 += charArr1[index];
            sum2 += charArr2[index];
        }
        // in most cases it would return from here
        if (sum1 != sum2) {
            return false;
        }
        List<Character> charList1 = toList(charArr1);
        List<Character> charList2 = toList(charArr2);
        for (Character charValue : charList1) {
            charList2.remove(charValue);
        }
        return charList2.isEmpty();
    }

    private static List<Character> toList(char[] charArr) {
        assert charArr != null;
        List<Character> charList = new ArrayList<Character>();
        for (char ch : charArr) {
            charList.add(ch);
        }
        return charList;
    }
}

Related Tutorials