java集合

485 查看

集合的作用:
1,在类的内部,对数据进行组织
2,简单而快速的搜索大数量的条目
3,有的集合接口,提供了一系列排列有序的元素,并且可以在序列中间快速的插入或者删除有关元素
4,有的集合接口提供了映射的关系,可以通过关键字(key)去快速查找到对应的唯一对象,而这个关键字可以是任意的类型

为何选择集合而不是数组
数组长度固定,集合长度可变
数组只能通过下标访问,类型固定,而集合可以通过任意类型查找所映射的具体对象

collection map 是接口

Collection 接口,子接口以及实现类
Collection接口
1,是list set和queue接口的父接口
2,定义了可用于操作list set和queue的方法-增删改查

List接口以及实现类-ArrayList
1,List是元素有序并且可以重复的集合,被称为序列
2,list可以精确的控制每一个元素的插入位置,或删除某一个元素
3,ArrayList-数组序列,是list的一个重要实现类。
4,ArrayList底层是由数组实现的。

如何通过迭代器来遍历List
Iterator it =

            selectedCourses.iterator();
    while(it.hasNext()){
        course cr = (course) it.next();
        System.out.println(cr.id+","+cr.name);
    }

更改集合内容
selectedCourses.set(0, new course("5","michael"));

泛型中的元素,可以是任意类型的对象,(对象的引用)
如果把某个对象放入集合,则会忽略它的类型,把它当作object类处理
泛型规定某个集合只可以存放特定类型的对象,会在编译期间对其进行检查

set是元素无序并且不可重复的集合,被称为集
HashSet 是set的一个重要的实现类,哈希集 (无序并且不可重复)

因为set是无序的,所以不能用 List的get方法遍历取值,每一次遍历拿出来的都是不一样的值


在map中key值是不可以重复的,但是value值是可以重复的

每一个键key最多只能映射到一个值value
Map接口提供了分别返回key值集合,value值集合以及entry 键值对集合的方法
Map支持泛型,形如 Map<K,V>


keyset集合;
Set<String> keyset = student.keySet();

entry键值对
Set<Entry<String,Student>> entry = student.entrySet();

    for(Entry<String,Student> ent:entry){
        System.out.println(ent.getKey());
        System.out.println(ent.getValue());
    }

Map 也可以修改 put方法 Map
Student st = new Student("1","nmae");

    student.put("3", st);

重写HashCode方法判断是否相等
Object定义了HashCode方法,返回对象的hash码的值
当我们调用hashset的contains方法的时候,是先调用每一个元素的hashcode值返回hash码,在
每一个hash码相对的前提下调用equals方法去判断是否相等,只用在这两个都相等的前提下才能判断HashSet包含某个元素
eclipse可以自动生成hashcode和equals方法

comparable 接口

comparator 接口

java结合框架

Student类实现了comparable接口
public int compareTo(Student o) {
    // TODO Auto-generated method stub
    return this.id.compareTo(o.id);//利用id进行比较
}

public void testSortt(){
    List<Student> studentList =
            new ArrayList<Student>();
    Student s1 = new Student("1","s1");
    Student s2 = new Student("2","s2");
    Student s3 = new Student("3","s3");
    Student s4 = new Student("4","s4");
    Student s5 = new Student("5","s5");
    studentList.add(s1);
    studentList.add(s2);
    studentList.add(s3);
    studentList.add(s4);
    studentList.add(s5);
    Collections.sort(studentList);//student 类必须实现comparable接口
    for(Student s:studentList){
        System.out.println(s.id+","+s.name);
    }
}
public class StudentComparator implements Comparator<Student> {

public int compare(Student o1, Student o2) {
    //comparator定义临时的规则
    //如果是 0,两个对象相等
    //正数 o1>o2
    //负数 o1<o2
    return o1.name.compareTo(o2.name);
}

}

Collections.sort(studentList,new StudentComparator());
    for(Student s:studentList){
        System.out.println(s.id+","+s.name);
    }