关于java中的set的问题,set如何区分重复的元素?

关于java中的set的问题,set如何区分重复的元素?,java,arrays,list,set,hashset,Java,Arrays,List,Set,Hashset,有人能给我解释一下Set在java中是如何工作的吗?代码如下: List List=new ArrayList(); 增加第(1)款; 增加(2); 增加(3); List list1=新的ArrayList(); 清单1.添加(1); 清单1.添加(2); 清单1.添加(3); Set=newhashset(); 设置、添加(列表); set.add(列表1); 系统输出打印项次(套); int[]arr=新的int[3]; arr[0]=1; arr[1]=2; arr[2]=3; int

有人能给我解释一下Set在java中是如何工作的吗?代码如下:


List List=new ArrayList();
增加第(1)款;
增加(2);
增加(3);
List list1=新的ArrayList();
清单1.添加(1);
清单1.添加(2);
清单1.添加(3);
Set=newhashset();
设置、添加(列表);
set.add(列表1);
系统输出打印项次(套);
int[]arr=新的int[3];
arr[0]=1;
arr[1]=2;
arr[2]=3;
int[]arr1=新int[3];
arr1[0]=1;
arr1[1]=2;
arr1[2]=3;
Set set1=新的HashSet();
set1.添加(arr);
set1.add(arr1);
系统输出打印项次(set1);

输出: [[1, 2, 3]] [[I@7852e922, [I@6d06d69c]


我的问题是Set如何区分ArrayList/List?但不能区分ArrayList/List?我认为两者都是通过引用传递的,并且都是正确的对象?

当您向
集合添加新对象时,它会调用
SomeClass
类上的
equals()
方法。如果它返回false(即相同的值不存在),它将对象添加到集合中

这里调用AbstractList类的
//equals()方法,因为集合是//的列表类型
Set=newhashset();
设置、添加(列表);
set.add(list1);//list.equals(list1)此时为true
//这就是您获得唯一值的原因
---------------
//然而,当您添加一个纯java对象的纯数组时,equals()//会在通过引用进行比较的对象类上被调用
//这就是您无法获得唯一值的原因
Set set1=新的HashSet();
set1.添加(arr);
set1.add(arr1);

此外,在
Set
的情况下,employee是一个用户定义的类。如果我们不在employee类中使用自定义规则定义equals()方法,则继承
equals()<代码>对象> <代码>类将被调用,该集合将不具有唯一值。

区别在于它们如何定义哈希代码和等值。为了添加到该注释,java中的数组不重写<代码>对象。hash码< /COD>和<代码>对象。它本身。简而言之:如果
!A.equals(B)
             List<Integer> list = new ArrayList<>();
             list.add(1);
             list.add(2);
             list.add(3);
             List<Integer> list1 = new ArrayList<>();
             list1.add(1);
             list1.add(2);
             list1.add(3);
             Set<List<Integer>> set = new HashSet<>();
             set.add(list);
             set.add(list1);
             System.out.println(set);

             int[] arr = new int[3];
             arr[0] = 1;
             arr[1] = 2;
             arr[2] = 3;
             int[] arr1 = new int[3];
             arr1[0] = 1;
             arr1[1] = 2;
             arr1[2] = 3;
             Set<int[]> set1 = new HashSet<>();
             set1.add(arr);
             set1.add(arr1);
             System.out.println(set1);
         
    
// equals() method of AbstractList class is called here because the set is // of List type

Set<List<Integer>> set = new HashSet<>();
             set.add(list);
             set.add(list1); //list.equals(list1) is true at this point
// This is the reason you got unique values

---------------
// whereas when you add a plain array which is just a plain java object, equals() // gets called on Object class which compares by reference
// This is the reason you don't get unique values

Set<int[]> set1 = new HashSet<>();
             set1.add(arr);
             set1.add(arr1);