Java TreeSet,HashSet 和 HashMap 可以使用 equals() 比较

问题

TreeSet,HashSet 和 Map 集合可以用 equals() 吗?

解答

可以用 euquals(Object o) 来反映接口类型和元素是否相同,且与输入顺序无关;

import java.util.HashMap;
import java.util.HashSet;
import java.util.TreeSet;

public class test {
    public static void main(String[] args) {
        TreeSet ts = new TreeSet();
        ts.add('3');
        ts.add('4');
        TreeSet ts1 = new TreeSet();
        ts1.add('3');
        ts1.add('4');
        TreeSet ts2 = new TreeSet();
        ts2.add('4');
        ts2.add('3');
        System.out.println(ts.equals(ts1));//true
        System.out.println(ts1.equals(ts2));//true
        System.out.println("-------------");
        HashSet hs = new HashSet();
        hs.add('3');
        hs.add('4');
        HashSet hs1 = new HashSet();
        hs1.add('3');
        hs1.add('4');
        HashSet hs2 = new HashSet();
        hs2.add('4');
        hs2.add('3');
        System.out.println(hs.equals(hs1));//true
        System.out.println(hs1.equals(hs2));//true
        System.out.println(ts1.equals(hs1));//true
        System.out.println("-------------");
        HashMap hm = new HashMap();
        hm.put('3', '3');
        hm.put('4', '4');
        HashMap hm1 = new HashMap();
        hm1.put('3', '3');
        hm1.put('4', '4');
        HashMap hm2 = new HashMap();
        hm2.put('4', '4');
        hm2.put('3', '3');
        System.out.println(hm.equals(hm1));//true
        System.out.println(hm1.equals(hm2));//true
        System.out.println(hs1.equals(hm2));//false
    }
}
发布了59 篇原创文章 · 获赞 60 · 访问量 1576

猜你喜欢

转载自blog.csdn.net/Regino/article/details/104553286