提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
两个字符数组是否等价
/** 时代Java公众号 提供 **/ //package com.nowjava; 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 * 时 代 Java 公 众 号 - nowjava.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(); }