Set接口 HashSet linkedHashSet hashcode ArrayList

Set集合不允许存储重复元素的原理

\Set接口的特点:
1.不允许存储重复的元素
2.没有索引,没有带索引的方法,也不能使用普通的for循环遍历
java.util.HashSet集合 implements Set接口
HashSet特点:
1.不允许存储重复的元素
2.没有索引,没有带索引的方法,也不能使用普通的for循环遍历
3.是一个无序的集合,存储元素和取出元素的顺序有可能不一致
4.底层是一个哈希表结构(查询的速度非常的快)
*/
public class Demo01Set {
public static void main(String[] args) {
Set set = new HashSet<>();
//使用add方法往集合中添加元素
set.add(1);
set.add(3);
set.add(2);
set.add(1);
//使用迭代器遍历set集合
Iterator it = set.iterator();
while (it.hasNext()){
Integer n = it.next();
System.out.println(n);//1,2,3
}
//使用增强for遍历set集合
System.out.println("-----------------");
for (Integer i : set) {
System.out.println(i);
}
}
//创建HashSet集合对象
HashSet set = new HashSet<>();
set集合报错元素唯一:
存储的元素(String,Integer,...Student,Person...),必须重写hashCode方法和equals方法
LinkedHashSet集合特点:
底层是一个哈希表(数组+链表/红黑树)+链表:多了一条链表(记录元素的存储顺序),保证元素有序
HashSet set = new HashSet<>();
set.add("www");
set.add("abc");
set.add("abc");
set.add("itcast");
System.out.println(set);//[abc, www, itcast] 无序,不允许重复
System.out.println(linked);//[www, abc, itcast] 有序,不允许重复
哈希值:是一个十进制的整数,由系统随机给出(就是对象的地址值,是一个逻辑地址,是模拟出来得到地址,不是数据实际存储的物理地址)
在Object类有一个方法,可以获取对象的哈希值
int hashCode() 返回该对象的哈希码值。
hashCode方法的源码:
public native int hashCode();
native:代表该方法调用的是本地操作系统的方法

    toString方法的源码:
        return getClass().getName() + "@" + Integer.toHexString(hashCode());

package Java学习.chen.jeikou;

public class hashcode {
public static void main(String[] args) {
Person p1 = new Person();
int i = p1.hashCode();
System.out.println(i);//21685669
System.out.println(p1);//Java学习.chen.jeikou.Person@14ae5a5
}
}
*
String类的哈希值
String类重写Obejct类的hashCode方法
*/
String s1 = new String("abc");
System.out.println(s1.hashCode());//96354
System.out.println("陈东".hashCode());//1212628

​ //重写hashCode方法

@Override
public int hashCode() {
    return  1;
}

}

  • java.utils.Collections是集合工具类,用来对集合进行操作。部分方法如下:
    • public static boolean addAll(Collection c, T... elements):往集合中添加一些元素。

    • public static void shuffle(List<?> list) 打乱顺序:打乱集合顺序。
      /
      public class Demo01Collections {
      public static void main(String[] args) {
      ArrayList list = new ArrayList<>();
      //往集合中添加多个元素
      /
      list.add("a");
      list.add("b");
      list.add("c");
      list.add("d");
      list.add("e");*/

      //public static boolean addAll(Collection c, T... elements):往集合中添加一些元素。
      Collections.addAll(list,"a","b","c","d","e");

      System.out.println(list);//[a, b, c, d, e]

      //public static void shuffle(List<?> list) 打乱顺序:打乱集合顺序。
      Collections.shuffle(list);
      System.out.println(list);//[b, d, c, a, e], [b, d, c, a, e]
      }

}

posted @ 2021-05-13 10:57  陈诚成  阅读(84)  评论(0)    收藏  举报