java自学笔记12:java中的集合框架(上)

一.集合框架

1.概念与作用
2.体系结构
3.实际应用

集合的概念:
现实生活中:很多的事物凑在一起
数学中的集合:具有共同属性的事物的总体
java中的集合类:是一种工具类,就像是容器,存储任意数量的具有共同属性的对象。

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

与数组的对比—为何选择集合而不是数组
1.数组的长度和容量都是固定的,集合的长度或容量是动态扩展的
2.数组只能通过下标访问元素,类型固定,而有的集合可以通过任意类型查找所映射的具体对象

java集合框架体系结构
Collection:存储的都是单身对象
List(序列)有序,ArrayList
Queue(队列)有序,LinkedList
Set(集)无序,HashSet

这里写图片描述

Map:存储的都是夫妇,成对出现
HashMap

这里写图片描述

二.Collection接口&List接口简介

1.Collection接口,子接口以及实现类
Collection接口是List,Set和Queue接口的父接口
定义了可用于操作List,Set和Queue的方法-增删改查

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

实现功能—模拟学生选课功能

*选择课程(往集合中添加课程)
*删除所选的某门课程(删除集合中的元素)
*查看所选课程
*修改所选课程

代码示例:

创建学生类和课程类

package com.vishuo.collection;

import java.util.HashSet;
import java.util.Set;//Set和List一样,都是Collection的子接口

/*
 * 学生类
 * 
 * */
public class Student {
  public String id;
  public String name;

  public Set courses;

  public Student(String id,String name){
      this.id = id;
      this.name = name;
      //实例化
      this.courses  =new HashSet();
  }
}
package com.vishuo.collection;

/*
 * 课程类:在实际开发中,要实现属性的私有化,通过setter和getter方法进行访问
 * */
public class Course {

    public String id;
    public String name;

    public Course(String id,String name){
        this.id = id;

        this.name = name;
    }
    public Course(){

    }
}
package com.vishuo.collection;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/*
 * 备选课程类
 * */

public class ListTest {
    /*
     * 用于存放备选课程的List
     */
    public List coursesToSelect;

    public ListTest() {
        this.coursesToSelect = new ArrayList();
    }
    /*
     * 用于往CoursesToSelect中添加备选课程
     */

    public void testAdd() {
        // 创建一个课程对象,并通过调用add方法,添加到备选课程List中
        Course cr1 = new Course("1", "数据结构");
        coursesToSelect.add(cr1);
        Course temp = (Course) coursesToSelect.get(0);// 对象存入集合都变成object类型,取出时需要类型转换
        ;
        System.out.println("添加了课程:" + temp.id + ":" + temp.name);

        Course cr2 = new Course("2", "C语音");
        coursesToSelect.add(0, cr2);
        Course temp2 = (Course) coursesToSelect.get(0);
        System.out.println("添加了课程:" + temp2.id + ":" + temp2.name);

        coursesToSelect.add(cr1);
        Course temp0 = (Course) coursesToSelect.get(2);// 对象存入集合都变成object类型,取出时需要类型转换
        ;
        System.out.println("添加了课程:" + temp0.id + ":" + temp0.name);

        /**
         * Course cr3 = new Course("3", "test"); coursesToSelect.add(4,cr3);
         * 会报数组下标越界异常
         * 
         * 添加了课程:1:数据结构Exception in thread "main" 添加了课程:2:C语音
         * java.lang.IndexOutOfBoundsException: Index: 4, Size: 2 at
         * java.util.ArrayList.rangeCheckForAdd(ArrayList.java:661) at
         * java.util.ArrayList.add(ArrayList.java:473) at
         * com.vishuo.collection.ListTest.testAdd(ListTest.java:35) at
         * com.vishuo.collection.ListTest.main(ListTest.java:41)
         */

        Course[] coures = { new Course("3", "离散数学"), new Course("4", "汇编语音") };
        coursesToSelect.addAll(Arrays.asList(coures));
        Course temp3 = (Course) coursesToSelect.get(3);
        Course temp4 = (Course) coursesToSelect.get(4);
        System.out.println("添加了两门课程:" + temp3.id + ":" + temp3.name + ";" + temp4.id + ":" + temp4.name);

        Course[] course2 = { new Course("5", "高等数学"), new Course("6", "大学英语") };
        coursesToSelect.addAll(2, Arrays.asList(course2));

        Course temp5 = (Course) coursesToSelect.get(2);
        Course temp6 = (Course) coursesToSelect.get(3);
        System.out.println("添加了两门课程:" + temp5.id + ":" + temp5.name + ";" + temp6.id + ":" + temp6.name);

    }

    /**
     * 取得List中的元素的方法
     * 
     * @author mac
     *
     */

    public void testGet() {
        int size = coursesToSelect.size();
        System.out.println("有如下课程待选:");
        for (int i = 0; i < size; i++) {
            Course cr = (Course) coursesToSelect.get(i);
            System.out.println("课程:" + cr.id + ":" + cr.name);
        }
    }

    /*
     * 通过迭代器来遍历List
     */
    public void testIterator() {
        // 通过集合的iterator方法,取得迭代器的示例
        Iterator it = coursesToSelect.iterator();
        System.out.println("有如下课程待选(通过迭代器访问):");
        while (it.hasNext()) {
            Course cr = (Course) it.next();
            System.out.println("课程:" + cr.id + ":" + cr.name);
        }
    }

    /*
     * 通过for each 方法访问集合元素
     */
    public void testForEach() {
        System.out.println("有如下课程待选(通过for each访问):");
        for (Object obj : coursesToSelect) {
            Course cr = (Course) obj;
            System.out.println("课程:" + cr.id + ":" + cr.name);
        }
    }

    /*
     * 修改List中的元素
     */
    public void testModify() {
        coursesToSelect.set(4, new Course("7", "毛概"));
    }

    /*
     * 删除List中的元素
     */
    public void testRemove() {
        // Course cr= (Course)coursesToSelect.get(4);
        // System.out.println("我是课程:"+cr.id+":"+cr.name+",我即将被删除");
        // coursesToSelect.remove(cr);
        // System.out.println("即将删除4位置上的课程!");
        // coursesToSelect.remove(4);
        System.out.println("即将删除4位置和5上的课程!");
        Course[] coures = { (Course) coursesToSelect.get(4), (Course) coursesToSelect.get(5) };
        coursesToSelect.removeAll(Arrays.asList(coures));
        System.out.println("成功删除课程!");
        testForEach();
    }

    /*
     * 往List中添加一些奇怪的东西
     */
    public void testType() {
        /*
         * System.out.println("能否往List中添加一些奇怪的东西呢!?");
        coursesToSelect.add("我不是课程,我只是一个无辜的字符串");

         * Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to com.vishuo.collection.Course
    at com.vishuo.collection.ListTest.testForEach(ListTest.java:105)
    at com.vishuo.collection.ListTest.main(ListTest.java:146)
         */


    }

    public static void main(String[] args) {
        ListTest lt = new ListTest();
        lt.testAdd();
        lt.testType();
        lt.testForEach();
        // lt.testGet();
        // lt.testIterator();
        // lt.testForEach();
        // lt.testModify();
        // lt.testForEach();
        // lt.testRemove();
    }
}

二.泛型

集合中的元素,可以是任意类型的对象(对象的引用)
:如果把某个对象放入集合,则会忽略他的类型,而把他当做Object处理

泛型则是规定了某个集合只可以存放特定类型的对象
:会在编译期间进行类型检查
可以直接按指定类型获取集合元素

注意:
1.泛型集合中的限定类型,不能使用基本数据类型。
2.可以通过使用包装类限定允许存入的基本数据类型。

代码示例:

创建Course的子类ChildCourse类

package com.vishuo.collection;

public class ChildCourse extends Course {


}
package com.vishuo.collection;

import java.util.ArrayList;
import java.util.List;

public class TestGeneric {

    /*
     * 带有泛型-Course的List的类型属性
     */
    public List<Course> courses;

    public TestGeneric(){
        this.courses = new ArrayList<Course>();
    }

    /*
     * 测试添加
     */
    public void testAdd(){
      Course cr1 = new Course("1","大学语文");
      courses.add(cr1);
      //泛型集合中,不能添加泛型规定的类型及其子类型以外的对象,否则会报错!
//    courses.add("能否添加进一些奇怪的东西呢?");
      Course cr2 =new Course("2","java基础");
      courses.add(cr2);
    }

    /*
     * 测试循环遍历
     */
    public void testForEach(){
        for(Course cr:courses){
            System.out.println(cr.id+":"+cr.name);
        }
    }

    /*
     * 泛型结合可以添加泛型的子类型的对象实例
     */
    public void testChild(){
        ChildCourse ccr = new ChildCourse();
        ccr.id = "3";
        ccr.name ="我是子类型的课程对象实例";
        courses.add(ccr);
    }

    /*
     * 泛型不能使用基本类型
     */
    public void testBasicType(){
        List<Integer> list = new ArrayList<Integer>();
        list.add(1);
        System.out.println("基本类型必须使用包装类作为泛型!"+list.get(0));
    }

    public static void main(String[] args){
        TestGeneric tg = new TestGeneric();
        tg.testAdd();
        tg.testForEach();
        tg.testChild();
        tg.testForEach();
        tg.testBasicType();
    }
}

学生选课—通过Set集合管理课程

Set接口及其实现类—HashSet
:Set是元素无序并且不可以重复的集合,被称为集
:HashSet—哈希集,是Set的一个重要实现类

这里写图片描述

案例功能说明:
:提供备选课程
:创建学生对象,并给该学生添加三门课程(添加在学生的courses—Set类型的属性中)
:显示备选课程
:循环三次,每次输入课程ID
:往学生的courses属性中添加与输入的ID匹配的课程
:输出学生选择的课程

修改Student类

package com.vishuo.collection;

import java.util.HashSet;
import java.util.Set;//Set和List一样,都是Collection的子接口

/*
 * 学生类
 * 
 * */
public class Student {
  public String id;
  public String name;

  public Set<Course> courses;

  public Student(String id,String name){
      this.id = id;
      this.name = name;
      //实例化
      this.courses  =new HashSet<Course>();
  }
}
package com.vishuo.collection;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class SetTest {

    public List<Course> coursesToSelect;

    public SetTest(){
        coursesToSelect = new ArrayList<Course>();

    }


    public void testAdd() {
        // 创建一个课程对象,并通过调用add方法,添加到备选课程List中
        Course cr1 = new Course("1", "数据结构");
        coursesToSelect.add(cr1);
        Course temp = (Course) coursesToSelect.get(0);// 对象存入集合都变成object类型,取出时需要类型转换
        ;
//      System.out.println("添加了课程:" + temp.id + ":" + temp.name);

        Course cr2 = new Course("2", "C语音");
        coursesToSelect.add(0, cr2);
        Course temp2 = (Course) coursesToSelect.get(0);
//      System.out.println("添加了课程:" + temp2.id + ":" + temp2.name);

//      coursesToSelect.add(cr1);
//      Course temp0 = (Course) coursesToSelect.get(2);// 对象存入集合都变成object类型,取出时需要类型转换
//      ;
//      System.out.println("添加了课程:" + temp0.id + ":" + temp0.name);

        /**
         * Course cr3 = new Course("3", "test"); coursesToSelect.add(4,cr3);
         * 会报数组下标越界异常
         * 
         * 添加了课程:1:数据结构Exception in thread "main" 添加了课程:2:C语音
         * java.lang.IndexOutOfBoundsException: Index: 4, Size: 2 at
         * java.util.ArrayList.rangeCheckForAdd(ArrayList.java:661) at
         * java.util.ArrayList.add(ArrayList.java:473) at
         * com.vishuo.collection.ListTest.testAdd(ListTest.java:35) at
         * com.vishuo.collection.ListTest.main(ListTest.java:41)
         */

        Course[] coures = { new Course("3", "离散数学"), new Course("4", "汇编语音") };
        coursesToSelect.addAll(Arrays.asList(coures));
        Course temp3 = (Course) coursesToSelect.get(2);
        Course temp4 = (Course) coursesToSelect.get(3);
//      System.out.println("添加了两门课程:" + temp3.id + ":" + temp3.name + ";" + temp4.id + ":" + temp4.name);

        Course[] course2 = { new Course("5", "高等数学"), new Course("6", "大学英语") };
        coursesToSelect.addAll(2, Arrays.asList(course2));

        Course temp5 = (Course) coursesToSelect.get(2);
        Course temp6 = (Course) coursesToSelect.get(3);
//      System.out.println("添加了两门课程:" + temp5.id + ":" + temp5.name + ";" + temp6.id + ":" + temp6.name);

    }

    /*
     * 通过for each 方法访问集合元素
     */
    public void testForEach() {
        System.out.println("有如下课程待选(通过for each访问):");
        for (Object obj : coursesToSelect) {
            Course cr = (Course) obj;
            System.out.println("课程:" + cr.id + ":" + cr.name);
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        SetTest st = new SetTest();
        st.testAdd();
        st.testForEach();
        //创建一个学生对象
        Student student = new Student("1","小敏");
        System.out.println("欢迎学生:"+student.name+"选课!");
        //创建一个Scanner对象,用来接收从键盘输入的课程ID
        Scanner console = new Scanner(System.in);

        for(int i = 0;i<3;i++){
            System.out.println("请输入课程ID");
            String courseId = console.next();
            for(Course cr: st.coursesToSelect){
                if(cr.id.equals(courseId)){
                    student.courses.add(cr);
                    /*
                     * Set中,添加某个对象,无论添加多少次
                     * 最终只会保留一个该对象(的引用)
                     * 并且,保留的是第一次添加的哪一个
                     */
//                  student.courses.add(cr);
                }
            }
        }
        st.testForEachForsET(student);
    }

    public void testForEachForsET(Student student){
        //打印输出,学生所选的课程!
        System.out.println("共选择了:" + student.courses.size() +"门课程");
        for(Course cr:student.courses){
            System.out.println("选择了课程:" +cr.id +":"+cr.name);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值