Collection集合体系
Map体系
●Java集合大致分为Set、List、Queue、Map四种体系。
●最常用的集合:HashSet、TreeSet、ArrayList、ArrayDeque、LinkedList、TreeMap
●Iterator接口也是Java集合框架的成员,但它与Collection系列,Map系列的集合不一样:Collection、Map系列集合主要用于盛装其他对象,而Iterator则主要用于遍历Collection集合中的元素,
Iterator对象也被称为迭代器。
HashSet
当向HashSet集合中存入一个元素时,HashSet会调用该对象的hashCode()方法来得到该对象的hashCode值,然后根据hashCode值决定该对象在HashSet中的存储位置。
HashSet集合判断两个元素相等的标准是两个对象通过equals()方法比较相等,并且两个对象的hashCode()方法返回值也相等。
具体的方法参见API文档,这里就不展示了。
HashSet去重的原理:1.hashCode,2.equals是否相同
可以通过覆写hashCode和equals方法改变其去重规则,进行自定义去重
TreeSet
与HashSet相比,TreeSet多了几个额外的方法
因为TreeSet中的元素是有序的,所以增加了访问第一个、前一个、后一个、最后一个元素的方法,并且提供了从三个TreeSet中截取子TreeSet的方法。
TreeSet加入元素时,必须加入同类型的对象,否则会发生ClassCastException异常,因为TreeSet会调用集合元素的compareTo()方法来比较元素之间的大小关系(自然排序)。
方法测试:
@Test
public void TreeSetTest(){
TreeSet ts=new TreeSet();
ts.add(2);
ts.add(5);
ts.add(-8);
ts.add(10);
System.out.println(ts);
System.out.println(ts.first());//输出-8
System.out.println(ts.last());//输出10
System.out.println(ts.headSet(5));//返回小于5的子集,不包含5,输出[-8,2]
System.out.println(ts.tailSet(5));//返回大于5的子集,如果Set中有5,子集也包含5,输出[5,10]
System.out.println(ts.subSet(-8,5));//返回值包括前面不包括后面,输出[-8, 2]
}
其他测试:
@Test
public void TreeSetAddObjTest(){
TreeSet ts=new TreeSet();
ts.add(5);
ts.add("hello");
System.out.println(ts);
}
测试结果:
如果加入的是实体对象,比如Student,则Student类必须实现Comparable接口,并重写compareTo()方法,
(这也时TreeSet去重的原理!!!)
Student类有姓名、年龄、性别三个属性,省略代码为get/set方法,如下:
public class Student implements Comparable{
@Override
public int compareTo(Object o) {
Student s= (Student) o;
return getAge()>s.getAge()?1:getAge()
}
}
标红代码表示:可以根据需要改变排序规则,这里是升序排列。
@Test
public void TreeSetAddObjTest(){
TreeSet ts=new TreeSet();
Student stu1=new Student("张三",23,"男");
Student stu2=new Student("zone",21,"男");
Student stu3=new Student("小镅",22,"女");
ts.add(stu1);
ts.add(stu2);
ts.add(stu3);
System.out.println(ts);
for(Object o:ts){
Student stu= (Student) o;
System.out.println(stu.getName()+"的年龄"+stu.getAge());
}
}
测试结果:
原文出自:https://my.csdn.net/qq_37094660(如需转载请注明出处)