在 Java 中找出兩個不同列表是否包含完全相同元素的簡便方法
如果兩個列表包含相同數量的元素且按順序相同,則它們相等。
假設我們有以下兩個列表 -
List<Integer>arrList1 = Arrays.asList(new Integer[] { 10, 20, 30, 45, 55, 70, 90, 100 }); List<Integer>arrList2 = Arrays.asList(new Integer[] {15, 25, 35, 50, 55, 75, 95, 120});
現在,讓我們找出這兩個列表是否相等 -
arrList1.equals(arrList2);
如果以上兩個列表具有相等的元素,則返回 TRUE,否則 FALSE 是返回值。
示例
import java.util.Arrays; import java.util.List; public class Demo { public static void main(String[] a) { List<Integer>arrList1 = Arrays.asList(new Integer[] { 10, 20, 30, 45, 55, 70, 90, 100 }); List<Integer>arrList2 = Arrays.asList(new Integer[] {15, 25, 35, 50, 55, 75, 95, 120}); List<Integer>arrList3 = Arrays.asList(new Integer[] { 10, 20, 30, 45, 55, 70, 90, 100}); System.out.println("Are List 1 and List2 equal? "+arrList1.equals(arrList2)); System.out.println("Are List 2 and List3 equal? "+arrList2.equals(arrList2)); System.out.println("Are List 1 and List3 equal? "+arrList1.equals(arrList3)); } }
輸出
Are List 1 and List2 equal? false Are List 2 and List3 equal? true Are List 1 and List3 equal? true
廣告