java学习日记20230414-Set接口
Set接口的常用方法和基本介绍
Set接口基本介绍:
- 无序(添加和取出的顺序不一致),没有索引;
- 不允许重复元素,所以最多包含一个null;
- JDK API中Set接口的实现类:AbstractSet,EnumSet,HashSet,TreeSet,LinkedHashSet,JobStateReasons等;
Set接口的常用方法:
和List接口一样,Set接口也是Collection的字接口因此常用方法和Collection接口一样;
Set接口的遍历方式:
1.可以使用迭代器;
2.通过增强for循环;
3.不能使用索引的方式来获取;
public class SetMethod {
public static void main(String[] args) {
//以set接口的实现类HashSet方法
//set接口对象不能存放重复的元素,可以添加一个set元素
//set接口对象存放的数据是无序(添加的顺序和取出的顺序不一致)
//取出的顺序虽然不是添加的顺序,但是固定的
Set set = new HashSet();
set.add("john");
set.add("lucy");
set.add("john");
set.add("jack");
set.add(null);
set.add(null);
set.add("marry");
System.out.println(set);
//遍历
Iterator iterator = set.stream().iterator();
while(iterator.hasNext()){
Object o = iterator.next();
System.out.println(o);
}
for (Object o :set) {
System.out.println(o);
}
//删除
set.remove("nuldd dl");
System.out.println(set);
}
}
HashSet的全面说明:
- HashSet实现了Set接口
- HashSet实际上是HashMap
- 可以存放一个null值
- 不保证元素是有序的,取决于hash后,再确定索引的结果
- 不能有重复元素/对象
模拟链表+数组
public class HashSet_ { public static void main(String[] args) { Set hashSet = new HashSet(); //在执行add方法后会返回一个boolean值,成功为true,失败为false boolean set1 = hashSet.add(null); boolean set2 = hashSet.add(null); System.out.println(set1); //dog对象不同 hashSet = new HashSet(); hashSet.add("lucy"); hashSet.add("lucy"); hashSet.add(new Dog("tom")); hashSet.add(new Dog("tom")); System.out.println(hashSet); //无法加入,*****判断add重复机制****** hashSet.add(new String("hsp")); hashSet.add(new String("hsp")); System.out.println(hashSet); //HashMap底层是数组+链表+红黑树 //模拟简单的数组+链表 Node[] table = new Node[16]; System.out.println("table="+table); Node john = new Node("john", null); Node jack = new Node("jack", null); table[2] = john; john.next = jack; System.out.println(table[2]); Node rose = new Node("rose", null); jack.next = rose; System.out.println(table[2]); Node lucy = new Node("lucy", null); table[3] = lucy; System.out.println(Arrays.toString(table)); } } class Dog{ private String name; public Dog(String name) { this.name = name; } @Override public String toString() { return "Dog{" + "name='" + name + '\'' + '}'; } } class Node{//结点,存储数据,可以指向下一个结点 Object item; Node next; public Node(Object item, Node next) { this.item = item; this.next = next; } @Override public String toString() { return "Node{" + "item=" + item + ", next=" + next + '}'; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义