集合set
1、Java中使用set接口描述一个集合,集合set是collection的子接口,set不允许其数据元素重复出现。
2、方法
3、Set接口的交集、并集、差集运算
4、Treeset
TreeSet是一个有序集合,其元素按照升序排列,默认是按照自然顺序排列,也就是说TreeSet中的对象元素需要实现Comparable接口。TreeSet类中跟HashSet类一样也没有get()方法来获取指定位置的元素,所以也只能通过迭代器方法来获取。
TreeSet虽然是有序的,但是并没有具体的索引,当插入一个新的数据元素的时候,TreeSet中原有的数据元素可能需要重新排序,所以TreeSet插入和删除数据元素的效率较低。
当我们使用TreeSet存储自定义类时,需要在自定义类中重写compareTo方法,以提供比对形式,否则TreeSet不能对用户自定义的类型进行正确的树状排序。
public class Employee implements Comparable<Employee>{
/*
* 使用treeset方法,必须实现comparable接口。(因为需要排序,所以要实现comparable接口)
* 否则会报错 classCaseException。
*/
public int compareTo(Employee emp) {
return salary.compareTo(emp.salary) == 0 ? 1 : salary.compareTo(emp.salary);
}
举例:
public class TreeSetTest {
public static void main(String[] args) {
Set<Employee> eSet = new TreeSet<Employee>();//采用接口回调的方法
eSet.add(new Employee("超群", "00001", new BigDecimal("32000")));
eSet.add(new Employee("古方", "00002", new BigDecimal("32000")));
eSet.add(new Employee("王原", "00003", new BigDecimal("48000")));
eSet.add(new Employee("周宇", "00004", new BigDecimal("45000")));
eSet.add(new Employee("唐僧", "00005", new BigDecimal("1")));
/*
* 添加元素,注意大数据类型的添加方法。
*/
for(Employee emp : eSet) {
System.out.println("==================>" + emp);
}
/*
* 遍历(加强for循环);
* 不可以用for(int i=0;i<=eSet.size();i++)这种,因为不能通过i来获取元素,因为没有get方法,只有list可以。
* 另一种就是可以采用迭代器(笔记74页,及视频194734);
*/
System.out.println("*************************************************>");
Iterator<Employee> iter = eSet.iterator();
while(iter.hasNext()) {
Employee emp = iter.next();
System.out.println("==================>" + emp);
/*
* 迭代器
*/
}
}
}