Bootstrap

java使用泛型判断两个List是否相等

package com.ping;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class TestMain {

    public static  <T extends Comparable<T>> boolean isEqualList(List<T> list1, List<T> list2){
        if(list1 == null && list2 == null) {
            return true;
        }
        if(list1 == null || list2 == null) {
            return false;
        }
        if(list1.size() != list2.size()) {
            return false;
        }
        list1 = new ArrayList<T>(list1);
        list2 = new ArrayList<T>(list2);

        Collections.sort(list1);
        Collections.sort(list2);

        return list1.equals(list2);
    }


    public static void main(String[] args) {
        List<Integer> list1 = Arrays.asList(1, 2, 3, 3, 4);
        List<Integer> list2 = Arrays.asList(3, 2, 1, 4, 3);
        List<Integer> list3 = Arrays.asList(1, 2, 3, 4);
        List<Integer> list4 = Arrays.asList(1, 2, 3, 4, 5);

        List<String> list5 = Arrays.asList("张三","李四", "王五", "赵六");
        List<String> list6 = Arrays.asList("张三","李四", "李四","王五");

        System.out.println(isEqualList(list1, list2)); // true
        System.out.println(isEqualList(list1, list3)); // false
        System.out.println(isEqualList(list1, list4)); // false

        System.out.println(isEqualList(list5, list6)); // false
    }
}
;