集合的基本使用


一、集合的特点

  1.长度随着元素个数自动变化

  2.集合只能存放引用数据类型,如果需要存放基本数据类型,则需要封装成包装类

  3.java中有很多的集合,最常用的是ArrayList

二、集合的创建方法

  1.什么是泛型

    泛型本质上是提供类型的“类型参数”,也就是参数化类型。我们可以为类、接口或方法指定一个类型参数,通过这个参数限制操作的数据类型,从而保证类型转换的绝对安全。

  2.JDK7以前的写法:

    ArrayList list = new ArrayList();

  3.JDK7以后:

    ArrayList list = new ArrayList<>(); (后面不需要泛型)

  4.在输出时,自动调用toString方法,在打印的时候会拿[]将所有元素包裹

三、ArrayList集合的方法

方法名称说明
E get(int index)获取此集合中指定索引位置的元素,E 为集合中元素的数据类型
int index(Object o)返回此集合中第一次出现指定元素的索引,如果此集合不包含该元
素,则返回 -1
int lastIndexOf(Object o)返回此集合中最后一次出现指定元素的索引,如果此集合不包含该
元素,则返回 -1
E set(int index, Eelement)将此集合中指定索引位置的元素修改为 element 参数指定的对象。
此方法返回此集合中指定索引位置的原元素
List subList(int fromlndex, int tolndex)返回一个新的集合,新集合中包含 fromlndex 和 tolndex 索引之间
的所有元素。包含 fromlndex 处的元素,不包含 tolndex 索引处的
元素

1.添加元素(增)

        list.add("AAA"); //           会返回一个True,可以不接收
        list.add("BBB");
        list.add("CCC");
        list.add("DDD");
        list.add("EEE");
        list.add("FFF");

2.删除元素(删)

        //删除元素1
        list.remove("BBB");//      会返回一个True,可以不接收
        System.out.println(list);
        //删除元素2
        list.remove(2);//     会返回被删除的元素,可以不接收
        System.out.println(list);

3.修改元素(改)

        //修改元素
        list.set(1, "BBB");//           会返回旧值,可以不接收
        System.out.println(list);

4.查找元素(查)

        //查询元素
        System.out.println(list.get(3));

5.简单遍历

        //遍历
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }

四、综合练习

    主程序

        //----------------------------------------------------综合练习---------------------------------------------
        //    一、定义一个集合,添加字符串,并进行遍历
        //        遍历格式参照:[元素1,元素2,元素3]
        ArrayList<String> aL = new ArrayList<>();
        aL.add("aaa");
        aL.add("bbb");
        aL.add("ccc");

        //方法一
        StringJoiner sj = new StringJoiner(",", "[", "]");
        for (int i = 0; i < aL.size(); i++) {
            sj.add(aL.get(i));
        }
        System.out.println(sj.toString());

        //方法二
        System.out.print("[");
        for (int i = 0; i < aL.size(); i++) {
            if (i == aL.size() - 1) {
                System.out.print(aL.get(i));
            } else {
                System.out.print(aL.get(i));
                System.out.print(",");
            }
        }
        System.out.print("]\n");


        //    二、定义一个集合,添加数字,并进行遍历
        //        遍历格式参照:[元素1,元素2,元素3]
        //包装类:
        //char >>  Character
        //int  >>  Integer
        //其他数据类型的包装类为首字母大写
        ArrayList<Integer> integerArrayList = new ArrayList<>();
        integerArrayList.add(111);
        integerArrayList.add(222);
        integerArrayList.add(333);
        System.out.println(integerArrayList);//           遍历方法相同,不再重复


        //    三、定义一个集合,添加一些学生对,并进行遍历
        //        学生类的属性为姓名,年龄。
        //Student类需要自己定义
        ArrayList<Student> studentList = new ArrayList<>();
        Student s1 = new Student("张三", 15);
        Student s2 = new Student("李四", 16);
        Student s3 = new Student("王五", 17);
        Student s4 = new Student("赵六", 18);
        studentList.add(s1);
        studentList.add(s2);
        studentList.add(s3);
        studentList.add(s4);
        //遍历
        for (int i = 0; i < studentList.size(); i++) {
            System.out.printf("学生名称:%s  年龄:%d\n", studentList.get(i).getName(), studentList.get(i).getAge());
        }

        //通过姓名查找学生是否存在并返回索引
        System.out.println(contains(studentList, "王五"));

        //返回未成年人的姓名
        System.out.println(isOverAge(studentList, 18));


    }

    public static int contains(ArrayList<Student> list, String name) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getName().equals(name)) {
                return i;
            }
        }
        return -1;
    }

    public static StringJoiner isOverAge(ArrayList<Student> list, int age) {
        StringJoiner sj2 = new StringJoiner(",", "[", "]");
        for (int i = 0; i < list.size(); i++) {
            String name = list.get(i).getName();
            if (contains(list, name) >= 0) {
                if (list.get(contains(list, name)).getAge() < age) {
                    sj2.add(list.get(contains(list, name)).getName());
                }
            }
        }
        return sj2;
    }

    Student.java


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() {
    }

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

学生信息管理系统

    主程序

public class javaDevelop {
    public static void main(String[] args) {
        Scanner sc1 = new Scanner(System.in);
        ArrayList<Student> studentList = new ArrayList<Student>();
        do{
            System.out.printf("-------------欢迎来到QC学生管理系统----------------\n" +
                                "1:添加学生\n" +
                                "2:删除学生\n" +
                                "3:修改学生\n" +
                                "4:查询学生\n" +
                                "5:退出\n" +
                                "请输入您的选择:");
        }while(mainLoop(studentList,sc1.nextInt()));

    }
    public static boolean mainLoop(ArrayList<Student> list,int choose){
        Scanner sc2 = new Scanner(System.in);
        switch(choose){
            case 1:
                list.add(addStudent(list));
                if(list.get(list.size() - 1) == null){
                    list.remove(list.size() - 1);
                }
                break;
            case 2:
                System.out.println("请输入需要删除的学生id:");
                if(removeStudent(list,sc2.nextInt())){
                    System.out.println("已经成功删除该id对应的学生");
                    break;
            }else{
                    System.out.println("删除失败,id不存在!");
                    break;
                }
            case 3:
                System.out.println("请输入需要修改的id:");
                if(changeStudent(list,sc2.nextInt())){
                    System.out.println("修改成功");
                    break;
                }else{
                    System.out.println("修改失败,id不存在!");
                    break;
                }
            case 4:
                if(list.size() > 0) {
                    System.out.printf("ID\t\t姓名\t年龄\t家庭住址\n");
                    for (int i = 0; i < list.size(); i++) {
                        System.out.printf("%d\t\t%s\t\t%d\t\t%s\n", list.get(i).getId(), list.get(i).getName(), list.get(i).getAge(), list.get(i).getLocation());
                    }
                }else{
                    System.out.println("你还未录入信息,请录入后重试");
                }
                break;
            case 5:
                return false;
            default:
                System.out.println("命令不存在,请重试!");
                break;
        }
        return true;
    }
    public static Student addStudent(ArrayList<Student> list){
        Scanner sc3 = new Scanner(System.in);
        Student student = new Student();
        System.out.println("请输入id:");
        int id = sc3.nextInt();
        if(checkId(list,id) == -1) {
            student.setId(id);
            System.out.println("请输入姓名:");
            student.setName(sc3.next());
            System.out.println("请输入年龄:");
            student.setAge(sc3.nextInt());
            System.out.println("请输入家庭住址:");
            student.setLocation(sc3.next());
            return student;
        }else{
            System.out.println("该ID已存在!");
            return null;
        }
    }
    public static boolean removeStudent(ArrayList<Student> list,int id){
        int index = checkId(list,id);
        if(index >= 0){
            list.remove(index);
            return true;
        }
        return false;
    }
    public static boolean changeStudent(ArrayList<Student> list,int id){
        int index  = checkId(list,id);
        if(index == -1){
            return false;
        }else {
            Scanner sc3 = new Scanner(System.in);
            do {
                System.out.println("请输入修改后的id:");
                int changeID = sc3.nextInt();
                if(checkId(list,changeID) == -1){
                    list.get(index).setId(changeID);
                    break;
                }else{
                    System.out.println("这个id已经存在,请更换id后重试!");
                }
            }while(true);
            System.out.println("请输入修改后的姓名:");
            list.get(index).setName(sc3.next());
            System.out.println("请输入修改后的年龄:");
            list.get(index).setAge(sc3.nextInt());
            System.out.println("请输入修改后的家庭住址:");
            list.get(index).setLocation(sc3.next());
            return true;
        }
    }
    public static int checkId(ArrayList<Student> list, int id){
        for (int i = 0; i < list.size(); i++) {
            if(list.get(i).getId() == id){
                return i;
            }
        }
        return -1;
    }
}

    Student.java


public class Student {
    private int id;
    private String name;
    private int age;
    private String location;

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

    public Student() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    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 String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }
}