集合——Set集合

Set集合

    Set集合中元素是无序的,不能够重复,在Set集合中存储的对象,不存在两个对象equals比较为true的状况。
java

    1)HashSet和TreeSet是Set集合中的两个实现类,分别用hash表和二叉树的方式实现Set集合,HashSet是经过散列集合实现Set的。
算法

    2)Set集合中没有get(int index)方法,不能像在List集合中,经过下标去获得对应的元素。若是想要的到元素,则使用Iterator迭代器。
spa

    3)向Set集合中添加元素 能够使用add()方法,可是增长的元素不会再集合末尾添加,由于Set集合中元素是无序的。code

Set<String> set = new HashSet<String>() ;    //多态
set.add("a");
set.add("b");
set.add("c");
//普通循环,使用Iteraotr迭代器迭代
Iterator it = (String)set.iterator() ;
while(it.hasNext()){
    String str = (String)it.next() ;
    System.out.println(str) ;
}
//加强for循环遍历Set集合
for(String str:set){
    System.out.println(str) ;
}

    4)hashCode对HashSet的影响。若是咱们不重写hashCode,那么咱们使用的就是Object提供的,而该方法是返回地址。也就是不一样的对象,hashCode不一样。
对象

    5)对于重写了equals方法的对象,强烈要求重写继承自Object类的hashCode方法,由于是否重写hashCode方法对操做集合有影响。
继承

    6)重写hashCode须要注意两点:
get

        ①与equals方法的一致性,经过equals方法比较返回为true的对象,其hashCode的方法返回的对象一致。
hash

        ②hashCode方法返回的值应该符合hash算法要求。
it

    7)boolean contains(Object obj)方法:查看对象是否存在Set集合中。for循环

Set<Point> set = new HashPoint<Point>() ;
//Point point = new Point(1,2) ;    set.add(point) ;
set.add(new Point(1,2));
set.add(new Point(3,4));
System.out.println(set.contains(new Point(1,2)));

    8)

Set<Point> set= new HashSet<Point>() ;
Point p1 = new Point(1,2);
Point p2 = new Point(3,4);
System.out.println("两个对象是不是一个对象"+(p1==p2));
System.out.println("两个对象内容是否相同"+(p1.equals(p2)));
System.out.println("两个对象hashCode是否相同"+(p1.hashCode()==p2.hashCode()));
    set.add(p1);
    set.add(p2);
   System.out.println("hashSet集合中元素个数"+set.size()) ;
   for(Point p:set){
       System.out.println(p) ;
   }

    9)Set集合中保存不一样对象时,不会保存既hashCode()相同又equals相同的对象,缺一不可,不然HashSet不认为他们是重复的值。