本章内容
1. Set
1.1 特点
1.2 遍历
1.2.1 foreach
1.2.2 迭代器
1.3 常用实现类
HashSet
TreeSet
自然比较接口: java.lang.Comparable
比较器: java.util.Comparaton
思维导图
Set
特点:无序、对象不能重复
遍历 :1 foreach
2 迭代器
public static void main(String[] args) {
//Set集合的特点:1.无序
Set s = new HashSet();
s.add("张三");
s.add("李四");
s.add("王五");
s.add("赵六");
//只有两种遍历方式 foreach
for (Object object : s) {
System.out.println(object);
}
System.out.println("---------------------------------------");
//Set集合的特点:2.元素不能重复
s.add("张三");
for (Object object : s) {
System.out.println(object);
}
System.out.println("---------------------------------------");
//遍历方式 2.迭代器
Iterator it = s.iterator();
while(it.hasNext()) {
Object next = it.next();
System.out.println(next);
}
}
常用实现类
1. HashSet
2. TreeSet 根据某种(规则)对里面的元素进行排序
public static void main(String[] args) {
Set<String> set = new TreeSet<String>();
//根据某种(规则)对里面的元素进行排序
set.add("s");
set.add("h");
set.add("a");
set.add("b");
set.add("i");
for (String string : set) {
System.out.println(string);
}
}
自然比较接口: java.lang.Comparable (实体类)
public int compareTo(User o) {
// int i = this.getId()-o.getId();
//大于0 顺序 小于0 倒序 等于0不会添加
int i = this.getName().hashCode()-o.getName().hashCode();
return i;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((sex == null) ? 0 : sex.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (sex == null) {
if (other.sex != null)
return false;
} else if (!sex.equals(other.sex))
return false;
return true;
}
比较器: java.util.Comparaton
String以AscII码进行比较,返回差值
public class NameComparator implements Comparator<User> {
@Override
public int compare(User o1, User o2) {
if(o1.getName().hashCode()-o2.getName().hashCode()>0) {
return 100;
} else if(o1.getName().hashCode()-o2.getName().hashCode()<0) {
return -100;
} else{
return 0;
}
}