您的位置:首页 > 职场人生

黑马程序员——Set实现类、Collections工具类

2015-08-12 09:10 489 查看
------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com"
target="blank">java培训</a>、期待与您交流! ----------

1、Set

    Set的特点:

        元素无序,唯一。

        注意:这里的无序是指存储和取出顺序不一致。

 

2、HashSet

(1)HashSet:无序唯一。

    HashSet底层数据结构是哈希表。

(2)用HashSet集合储存自定义对象时,并没有保证元素的唯一性,想要保证应该怎么办? 

    通过分析我们发现是add方法出问题了,并且跟以下这个判断有关

        e.hash == hash && ((k = e.key) == key || key.equals(k))

    它依赖两个方法:hashCode()和equals()

    顺序:

        首先,判断hashCode()值是否相同。

            相同:

                继续走equals()方法,根据其返回值:

                    true:说明元素重复,不添加到集合。

                    false:说明元素不重复,添加到集合。

            不同:直接添加到集合。

(3)怎么重写hashCode()和equals()方法呢?

    hashCode():

        把对象的所有成员变量值相加即可。

        如果是基本类型,就加值。如果是引用类型,就加哈希值。

    equals():

        A:this==obj

        B:!(obj instanceof Student)

        C:所有成员变量的值比较。基本类型用==,引用类型用equals()。

案例:

package com.set.hashset;//学生类
public class Student {

private String name;
private int age;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}

public Student() {
super();

}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.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;
Student other = (Student) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}

}
package com.set.hashset;
import java.util.HashSet;
/**
* HashSet储存自定义对象,并去除重复
*/
public class HashSetTest {

public static void main(String[] args) {

HashSet<Student> hs = new HashSet<Student>();

hs.add(new Student("liubei", 34));
hs.add(new Student("zhangfei", 28));
hs.add(new Student("zhangfei", 28));
hs.add(new Student("guanyu", 40));
hs.add(new Student("guanyu", 41));
hs.add(new Student("guanyu", 30));
hs.add(new Student("zhaoyun", 20));

for(Student s : hs){
System.out.println(s.getName()+"\t"+s.getAge());
}

}
}

     

3、TreeSet

(1)TreeSet的特点 

     可以对集合中的元素进行排序。

       

(2)TreeSet怎么保证元素排序?

    排序:底层结构是二叉树。按照树节点进行存储和取出。

    两种实现:

        1、自然排序 

            让对象所属的类实现Comparable接口,并重写接口中的compareTo方法,无参构造

             在自然排序中,如何保证排序和唯一性?   

                根据 compareTo 的返回值:   

                    正数:说明元素大,往后放。

                    负数:说明元素小,往前放。

                      0 :元素就不添加到集合中,这就是保证唯一性的原理。

        2、比较器接口排序(集合具备比较性)

            TreeSet的带参构造,要求构造方法接收一个实现了Comparator接口的对象。

                使用方式:

                1、排序使用多次:创建一个类实现 Comparator 接口,并重写 compare 方法

                                 将实现类的对象当做参数传给 TreeSet()

                 2、排序只使用一次:使用匿名内部类

            唯一:根据 int compare(T o1,T o2) 方法的返回值是否为0,0不加入集合。

            注意:

            推荐使用比较器接口排序

            原因:开发原则:对修改关闭,对扩展开放

Comparator 接口使用演示:

package com.comparator;

import java.util.Comparator;
import java.util.TreeSet;

public class ComparatorTest {

public static void main(String[] args) {

//排序并查重,使用匿名内部类
TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {

@Override
public int compare(Student s1, Student s2) {
int num = s1.getAge() - s2.getAge();
int num2 = (num == 0) ? (s1.getName().compareTo(s2.getName())) : num;

return num2;
}
});

Student s1 = new Student("asdff", 12);
Student s2 = new Student("bb", 23);
Student s3 = new Student("cc", 43);
Student s4 = new Student("cc", 43);
Student s5 = new Student("ddd", 33);
Student s7 = new Student("ddd", 23);
Student s6 = new Student("dddd", 43);

ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
ts.add(s5);
ts.add(s6);
ts.add(s7);

for (Student s : ts) {
System.out.println(s.getName() + "***" + s.getAge());
}
}

}


(3)TreeSet存储Integer讲解唯一和排序 

    TreeSet 底层结构:二叉树形结构

    

    那么,Treeset是如何存储数据的呢?

        A:把第一个存储进去的数据作为根节点

        B:把数据依次和根节点进行比较

            大了,往右放

            小了,向左放

            相等,把后来的数据扔掉

    从二叉树结构中取数据的内存规则

        原则:从每个节点的左边开始,遵循原则  左 中 右

4、Collection体现的集合总结

(1) Collection

        |--List (有序,元素可重复)

                |--ArrayList

                    底层数据结构是数组,查询快,增删慢

                    线程不安全,效率高。

                |--LinkedList

                    底层数据结构是链表,查询慢,增删快

                    线程不安全,效率高。

                |--Vector

                    底层数据结构是数组,查询快,增删慢

                    线程安全,效率低。

        |--Set (元素唯一)

                |--HashSet

                    底层数据结构是哈希表。

                    如何保证元素唯一性呢?

                    依赖两个方法。hashCode()和equals()。

                    以后都自动生成。

                |--TreeSet

                    底层数据结构是二叉树。

                    如何保证元素唯一性呢?如何保证元素排序呢?

                    根据返回值是否是0,判断元素是否重复。

                    排序有两种方案:

                        元素具备比较性 实现Comparable接口

                        集合具备比较性 实现Comparator接口

 

(2)在集合中的数据结构问题

    ArrayXxx:底层数据结构是数组。查询快,增删慢。

    LinkedXxx:底层数据结构是链表。查询慢,增删快。

    HashXxx:底层数据结构是哈希表。跟两个有关。hashCode()和equals()

    TreeXxx:底层数据结构是二叉树。两种排序方式。Comparable接口和Comparator接口

 

(3)什么时候,使用哪种Collection集合。

    元素唯一吗?

        唯一:

            Set

                需要排序吗?

                    需要:TreeSet

                    不需要:HashSet

                不知道,用HashSet。

        不唯一:

            List

                需要安全码?

                    需要:Vector

                    不需要:ArrayList和LinkedList

                        查询多:ArrayList

                        增删多;LinkedList

                        不知道,用ArrayList。

4、Collections工具类的使用



(1)面试题:Collection和Collections的区别?

        A:Collection是Collection体系的顶层接口,里面定义了这个体系中的共性方法.

        B:Collections是针对Collection集合操作的工具类 里面一定了一些对集合操作的方法 。比如 排序,查找,反转,最值,置换

(2)Collections 中的方法
    1. public static void sort ( List list )
        排序
    2. public static <T> int binarySearch( List list, T key )
        二分查找
    3. public static void reverse( List list )
        反转
    4. public static T max( Collection coll )
        最大值
    5. public static void shuffle( List list )
        随机置换.

使用演示:

package com.collection;

import java.util.ArrayList;
import java.util.Collections;

public class CollectionsDemo {
public static void main(String[] args) {

// 创建集合对象
ArrayList<Integer> array = new ArrayList<Integer>();
// 添加元素
array.add(60);
array.add(25);
array.add(38);
array.add(213);
array.add(99);
array.add(22);

System.out.println("array:" + array);

// 排序
// public static void sort(List list)
Collections.sort(array);
System.out.println("array:" + array);

// 二分查找
// public static <T> int binarySearch(List list,T key)
// [22, 25, 38, 60, 99, 213]
int index = Collections.binarySearch(array, 60);
System.out.println("index:" + index);

// 反转
// public static void reverse(List list)
// [60, 25, 38, 213, 99, 22]
Collections.reverse(array);
System.out.println("array:" + array);

// 最大值
// public static T max(Collection coll)
Integer i = Collections.max(array);
System.out.println(i);

// 随机置换:public static void shuffle(List list)
Collections.shuffle(array);
System.out.println("array:" + array);

}
}


------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: