1. Set
1.1 特点:无序、对象不能重复
1.2 遍历
1.2.1 foreach
1.2.2 迭代器
//Set集合的特点 1.无序
Set set = new HashSet();
set.add("a");
set.add("王某");
set.add("黄某");
set.add("李某");
//遍历方式只有两种 foreach
for (Object object : set) {
System.out.println(object);
}
//Set集合的特点:2.元素不能重复
set.add("a");
for (Object object : set) {
System.out.println(object);
}
//遍历方式 2.迭代器
System.out.println("----------------------");
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
Object next = iterator.next();
System.out.println(next);
}
package web_02;
import java.io.Serializable;
public class User implements Serializable{
private static final long serialVersionUID = 134314447435171651L;
private Integer id;
private String name;
private String sex;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public User() {
// TODO Auto-generated constructor stub
}
public User(Integer id, String name, String sex) {
this.id = id;
this.name = name;
this.sex = sex;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", sex=" + sex + "]";
}
// @Override
// public int compareTo(User o) {
int i = this.getId() - o.getId();
// //i有三种结果 大于0顺序,小于0倒序,等于0不会添加
// int i = this.getName().hashCode()-o.getName().hashCode();
// return i;
// }
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Set<User> set = new TreeSet<User>(new NameComparator());
//根据某种(规则)对里面的元素进行排序
set.add(new User(1, "罗霄","男"));
set.add(new User(1, "小俊","男"));
set.add(new User(2, "小红","女"));
set.add(new User(4, "a","男"));
set.add(new User(5, "d","男"));
set.add(new User(6, "b","女"));
for (User user : set) {
System.out.println(user);
}
}
1.3 常用实现类
HashSet
TreeSet:根据某种(规则)对里面的元素进行排序
自然比较接口: java.lang.Comparable
比较器: java.util.Comparator
String以AscII码进行比较,返回差值
LinkedHashSet:
1)元素是有顺序的
2)元素是不重复的
3)底层数据结构是按照链表的结构存储的 Linked
hashCode
队列 Queue:表示一个先入先出的数据结构(自行研究)
堆栈 Stack:表示一个先进后出的数据结构
压:push
弹:pop
Collections
public static void main(String[] args) {
String[] arrs =new String[] {"a","z","f","b"};
List<String> asList = Arrays.asList(arrs);
System.out.println(asList.getClass().getName());
for (String string : asList) {
System.out.println(string);
}
System.out.println("---------------------");
Collections.sort(asList);
for (String string : asList) {
System.out.println(string);
}
}