目录
目录
一、Set接口
1、set继承关系图
2、set方法
public class SetMethod {
public static void main(String[] args) {
//1. set集合无序(即添加顺序和取出顺序不一致)
//2. 不可重复
//3. 取出顺序虽然是无序的,但它是固定的
Set set = new HashSet();
set.add("john");
set.add("jack");
set.add("lucy");
set.add("lucy");
set.add(null);
System.out.println(set);//[null, john, lucy, jack]
}
}
二、HashSet说明
1.HashSet说明
import java.util.HashSet;
import java.util.Set;
/**
* @author: 程序员飞扬
* @description:
*/
public class HashSet01 {
public static void main(String[] args) {
Set set = new HashSet();
set.add("jack");
set.add("tom");
set.add("jerry");
System.out.println(set);//[tom, jerry, jack]
set.add("jack");
System.out.println(set);//加不进来 [tom, jerry, jack]
set.add(new Dog("jack"));
set.add(new Dog("jack"));
System.out.println(set);//不同对象能加入 [tom, jack, jack, jerry, jack]
set.add(new String("Rose"));
set.add(new String("Rose"));
System.out.println(set);//问题:能加进来吗? 后面源码分析
set.remove("tom");
System.out.println(set);//[jack, jack, jerry, jack]
}
}
2.数组链表模拟
/**
* @author: 程序员飞扬
* @description:数组链表模拟
*/
public class HashSetStructure {
public static void main(String[] args) {
Node2[] table = new Node2[6];
System.out.println(table);
Node2 john = new Node2("john", null);
table[2] = john;
Node2 jack = new Node2("jack", null);
john.next = jack;
Node2 sanguo = new Node2("三国",null);
table[4] = sanguo;
Node2 honglou = new Node2("红楼",null);
sanguo.next = honglou;
for (Node2 node2 : table) {
System.out.println(node2);
}
}
}
class Node2{
Object item;
Node2 next;
public Node2(Object item, Node2 next) {
this.item = item;
this.next = next;
}
@Override
public String toString() {
return "Node2{" +
"item=" + item +
", next=" + next +
'}';
}
}
输出:
null
null
Node2{item=john, next=Node2{item=jack, next=null}}
null
Node2{item=三国, next=Node2{item=红楼, next=null}}
null
3.HashSet扩容机制
4.HashSet源码解读
三、TreeSet
1.TreeSet的底层
tips:TreeSet的底层就是TreeMap
看源码:
2.TreeSet排序案例
import java.util.Comparator;
import java.util.TreeSet;
/**
* @author:程序员飞扬
* @公众hao:程序员飞扬
* @description:
*/
public class TreeSet_ {
public static void main(String[] args) {
/*TreeSet treeSet = new TreeSet(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return ((String)o2).compareTo((String)o1);//按首字母排序
}
});*/
TreeSet treeSet = new TreeSet(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return ((String)o2).length() - ((String)o1).length();//按长度排序,并且相同长度的的添加不进去
}
});
treeSet.add("a");
treeSet.add("fyt");
treeSet.add("col");
treeSet.add("z");
System.out.println(treeSet);
}
}