集合框架

来源:互联网 发布:知行乐学 编辑:程序博客网 时间:2024/06/06 08:29

Java2集合框架包括接口(interface),表示不同集合类型,是集合框架的基础;抽象类(abstract classes),对集合接口的部分实现,可扩展为自定义集合类。实现类(class),对接口的具体实现。

集合框架

  1. 接口
    (1) Collection接口是最基本的接口,代表一组允许重复的对象。
    (2) List接口继承了Collection接口以定义一个允许重复项的有序集合。该接口能够对列表的一部分进行处理,还添加了面向位置的操作。
    (3) Set接口继承Collection接口,而且他不允许集合中存在重复项,每个具体的Set实现类依赖添加对象的equals()方法检查独一性。Set接口没有引入新方法,所以Set就是一个Collection,只不过其行为不同。
    (4) Map接口不是Collection接口的继承。Map接口用于维护键/值对(key/value pairs)。该接口描述了从不重复的键到值得映射。拥有自己的内部排序机制。
    集合框架容器的元素类型都是Object。从容器中取得元素的时,必须把它转化成原来的类型。

  2. 实现类(学生管理系统实例)
    (1) List接口的实现类常用的有ArrayList和LinkedList。

ArrayList类封装了一个动态再分配的Object[]数组。每个ArrayList对象有一个capacity。这个capacity表示存储列表中元素的数组的容量。当元素添加到ArrayList的时候,capacity在常量时间内自动增加。ArrayList的优点在于允许快速随机访问和快速遍历,在List的中央位置插入或删除元素时效率很差。

package cn.edu.lcu.c06;/* * 创建一个学生类,包含学号、姓名、系别、年龄属性 */public class Student {    private int sID;    private String sName;    private int age;    private String dept;    /*     * 构造方法实现初始化     */    public Student(int sID, String sName, int age, String dept) {        this.sID=sID;        this.sName=sName;        this.age=age;        this.dept=dept;    }    public String getSName() {        return sName;    }    public void setSName(String name) {        sName=name;    }    public String getDept() {        return dept;    }    public void setDept(String dept) {        this.dept=dept;    }}
package cn.edu.lcu.c06;import java.util.ArrayList;import java.util.List;/* * 利用ArrayList类实现添加、获取学生信息功能 */public class StudentD1 {    /**     * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub        Student no1=new Student(2012001, "张华", 20, "信息管理");        Student no2=new Student(2012010, "王芳", 20, "软件工程");        List studentList=new ArrayList();        studentList.add(no1);        studentList.add(no2);        System.out.println("总人数:" + studentList.size() + "人");        for (int i=0; i<studentList.size(); i++) {            Student stu=(Student) studentList.get(i);            System.out.println(i+1 + ":" + stu.getDept() + "系--" + stu.getSName());        }    }}
package cn.edu.lcu.c06;import java.util.ArrayList;import java.util.List;/* * 利用ArrayList类实现信息的判断,添加,删除 */public class StudentD2 {    /**     * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub        Student no1=new Student(2012001, "张华", 20, "信息管理");        Student no2=new Student(2012010, "王芳", 20, "软件工程");        Student no3=new Student(2012030, "赵乐", 20, "网络工程");        List studentList=new ArrayList();        studentList.add(no1);        studentList.add(no2);        studentList.add(no3);        print(studentList);        if (studentList.contains(no3)) {            System.out.println("有姓名为赵乐的学生。");        } else {            System.out.println("没有姓名为赵乐的学生。");        }        studentList.remove(1);        System.out.println("\n删除第一个元素后:");        print(studentList);        studentList.remove(no3);        System.out.println("\n删除no3学生后:");        print(studentList);    }    public static void print(List stuList) {        System.out.println("总人数:" + stuList.size() + "人");        for (int i=0; i<stuList.size(); i++) {            Student stu=(Student) stuList.get(i);            System.out.println(i+1+":" + stu.getDept()+"系--" + stu.getSName());        }    }}

List接口的常用方法:
这里写图片描述

LinkedList类可以实现快速的在List中央位置插入和删除元素。另外LinkedList类提供了addFirst(), addLast(), getFirst(), getLast(),removeFirst(), removeLast()等方法,可以快速在LinkedList的首部和尾部实现插入和删除操作,因此LinkedList在栈和队列中使用很频繁。

package cn.edu.lcu.c06;import java.util.LinkedList;import java.util.List;/* * 利用LinkedList类实现快速的插入和删除 */public class StudentD3 {    /**     * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub        Student no1=new Student(2012001, "张华", 20, "信息管理");        Student no2=new Student(2012010, "王芳", 20, "软件工程");        Student no3=new Student(2012030, "赵乐", 20, "网络工程");        LinkedList studentList=new LinkedList();        studentList.add(no1);        studentList.addFirst(no2);        studentList.addLast(no3);        Student studentFirst=(Student) studentList.getFirst();        System.out.println("第一位学生的姓名是:" + studentFirst.getSName()   );        Student studentLast=(Student) studentList.getLast();        System.out.println("最后一位学生的姓名是:" + studentLast.getSName());        studentList.removeFirst();        studentList.removeLast();        /*         * 显示删除后的学生信息         */        System.out.println("\n删除后的学生人数为:" + studentList.size() + "人");        for (int i=0; i<studentList.size(); i++) {            Student stu=(Student) studentList.get(i);            System.out.println(i+1+":"+stu.getDept()+"系--"+stu.getSName());        }    }}

LinkedList常用方法:
这里写图片描述

在Collection接口中,iterator()方法返回Iterator。Iterator接口方法能以迭代方式逐个访问集合中的各个元素,并安全的从Collection中除去适当的元素。
常用方法:
Boolean hasNext() 判断是否存在另一个可以访问的元素
Object next() 返回要访问的下一个元素。如果到达集合结尾,则抛出NoSuchElementException异常
void remove() 删除上次访问返回的对象。必须紧跟在一个元素的访问后执行。如果上次访问后集合已被修改,方法将抛出IllegalStateException

/*     * 利用Iterator对象实现集合遍历     */    public static void print(List stuList) {        System.out.println("使用Iterator遍历,学生总数为:" + stuList.size() + "人");        Iterator t=stuList.iterator();        while(t.hasNext()) {            Student stu=(Student) t.next();            System.out.println(stu.getDept() + "系--" + stu.getSName());        }    }

(2) Set接口的实现类有HashSet和TreeSet。

HashSet常用于存储重复自由的集合。在添加HashSet的对象的时候需要采用适当分配哈希码的方式来实现hashCode()方法。

package cn.edu.lcu.c06;import java.util.HashSet;import java.util.Iterator;import java.util.List;/* * 利用HashSet实现元素的添加,删除等操作 * HashSet是以散列表进行存储的,输出的结果并不是按照输入的先后输出 * 由于使用了散列函数,查找元素的速度比较快 */public class StudentD4 {    /**     * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub        Student no1=new Student(2012001, "张华", 20, "信息管理");        Student no2=new Student(2012010, "王芳", 20, "软件工程");        Student no3=new Student(2012030, "赵乐", 20, "网络工程");        HashSet stuHashSet=new HashSet();        stuHashSet.add(no1);        stuHashSet.add(no2);        stuHashSet.add(no3);        System.out.println(stuHashSet.size());        System.out.println(stuHashSet.isEmpty());        System.out.println(stuHashSet.contains(no1));        String cz=stuHashSet.add(no3) ? "此对象不存在" : "已经存在";        System.out.println("测试是否可以添加对象  " + cz + "\n");        print(stuHashSet);        System.out.println("是否可删除?" + stuHashSet.remove(no3));        System.out.println("删除后:");        print(stuHashSet);    }    public static void print(HashSet stuHashSet) {        Iterator t=stuHashSet.iterator();        while(t.hasNext()) {            Student stu=(Student) t.next();            System.out.println(stu.getDept() + "系--" + stu.getSName());        }    }}

TreeSet的底层结构为一种有序集合,因此常用从集合中以有序的方式插入和抽取元素。

package cn.edu.lcu.c06;import java.util.Comparator;import java.util.Iterator;import java.util.TreeSet;public class TreeSetTest {    /**     * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub        TreeSet tr=new TreeSet(new Student.StudentComparator());        Student no1=new Student(2012001, "张华", 20, "信息管理");        Student no2=new Student(2012010, "王芳", 20, "软件工程");        Student no3=new Student(2012030, "赵乐", 21, "网络工程");        Student no4=new Student(2012030, "王亚", 21, "网络工程");        tr.add(no1);        tr.add(no2);        tr.add(no3);        tr.add(no4);        Iterator it=tr.iterator();        while(it.hasNext()) {            System.out.println(it.next());        }    }}class Student implements Comparable, Comparator {    private int sID;    private String sName;    private int age;    private String dept;    //构造方法实现初始化    public Student(int sID, String sName, int age, String dept) {        this.sID=sID;        this.sName=sName;        this.age=age;        this.dept=dept;    }    public int compareTo(Object o) {        Student st=(Student) o;        int result;        result=sID>st.sID ? 1 : (sID==st.sID ? 0 : -1); //学号相等就按姓名排序        return result;    }    public int compare(Object o1, Object o2) {        Student st1=(Student) o1;        Student st2=(Student) o2;        return st1.sName.compareTo(st2.sName);    }    //重写toString()方法,如果不重写,打印出来的是16进制代码    public String toString() {        return "学号=" + sID + ";    姓名=" + sName;    }    public static class StudentComparator implements Comparator {        public int compare(Object o1, Object o2) {            Student st1=(Student) o1;            Student st2=(Student) o2;            int result;            result=st1.sID>st2.sID ? 1 : (st1.sID==st2.sID ? 0 : -1);            if(result==0) {                result=st1.sName.compareTo(st2.sName);            }            return result;        }    }}

HashSet和TreeSet类的常用方法:
这里写图片描述

(3) 在Java的集合对象中,Map接口用于维护键/值对(key/value pairs),该接口描述了从不重复的键到值得映射。Map接口的实现有HashMap(用于快速查找)和TreeMap(用于排序)。

package cn.edu.lcu.c06;/* * 定义Student类,重写toString() */public class Student {    private String sName;    private int age;    private String dept;    public Student(String sName, int age, String dept) {        this.sName=sName;        this.age=age;        this.dept=dept;    }    public String getSName() {        return sName;    }    public void setSName(String name) {        sName=name;    }    public String getDept() {        return dept;    }    public void setDept(String dept) {        this.dept=dept;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age=age;    }    public String toString() {        return dept + "系," + "姓名:" + sName + "," + age + "岁\n";     }}
package cn.edu.lcu.c06;import java.util.HashMap;import java.util.Map;/* * 利用HashMap实现对学生信息的操作 */public class HashMapTest {    /**     * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub        Student stu1=new Student("张华", 20, "信息管理");        Student stu2=new Student("王芳", 20, "软件工程");        Student stu3=new Student("赵乐", 21, "网络工程");        Map stu=new HashMap();        //实现学生学号与学生基本信息的键-值映射,存放在HashMap中        stu.put(2012001, stu1);        stu.put(2012010, stu2);        stu.put(2012030, stu3);        //输出集合中的键集,值集和键-值对        System.out.println("键集:\n" + stu.keySet());        System.out.println("值集:\n" + stu.values());        System.out.println("键--值对:\n" + stu);        //返回当前集合中映射数量        System.out.println(stu.size());        //判断当前集合是否存在映射        System.out.println(stu.isEmpty());        //判断集合是否存在某键,存在则输出对应的值        if(stu.containsKey(2012001)) {            System.out.println(stu.get(2012001));        }        //删除集合中与key相关的映射        stu.remove(2012030);        System.out.println("键--值对:\n" + stu);        //删除集合中所有映射        stu.clear();        System.out.println("键--值对:\n" + stu);    }}

Map接口常用方法
这里写图片描述

3.算法
Java集合框架中的类Collections,实现了对集合操作的多种算法。具体可以参看JDK帮助文档。
http://www.oracle.com/technetwork/java/javase/documentation/jdk8-doc-downloads-2133158.html
http://docs.oracle.com/javase/8/docs/api/index.html

0 0
原创粉丝点击