想置空一个 集合. 于是,new了一个新的空集合 ,并让 新集合的地址 指向 旧集合.

问题描述:

想置空一个 ArrayList 集合. 于是,new了一个新的空集合 ,并让 新集合的地址 指向 旧集合.

相关代码:
public static void main(String[] args) {
        Student s = new Student(123,"asd",123,"asd");
        Student s1 = new Student(123,"asd",123,"asd");
        Student s2 = new Student(123,"asd",123,"asd");
        Student s3 = new Student(123,"asd",123,"asd");
        ArrayList studentList = new ArrayList<>();
        Scanner sc = new Scanner(System.in);
        studentList.add(s);
        studentList.add(s1);
        studentList.add(s2);
        studentList.add(s3);

        System.out.println("======================");
        for (int i = 0; i < studentList.size(); i++) {
            System.out.println(studentList.get(i));
        }
        System.out.println("======================");

       flush(studentList, sc);

        System.out.println("======================");

        for (int i = 0; i < studentList.size(); i++) {
            System.out.println(studentList.get(i));
        }
    }

    private static void flush( ArrayList studentList, Scanner sc) {
        System.out.println("Ensure Flush? Y / N");
        String yn = sc.next();
        if (yn.equalsIgnoreCase("Y")) {
            ArrayList newStudentArrayList = new ArrayList<>();
            studentList = newStudentArrayList;
        }
    }
运行结果如下图:

img

我的解答思路和尝试过的方法

我在 flush 里 已经让 studentList = newStudentArrayList; 了呀!

为什么 调用并执行完 flush() 方法后,程序回到main方法中,去遍历 原来的旧数组,还是有数据的. 不应该是空的吗?

我想要达到的结果

经过 flush() 方法的执行 之后,让旧数组置空嘛.

主要想问 为什么 原来的旧数组,还是有数据的?
希望看到的,能细心帮我解释下,我反应比较慢,感谢万分!

在线等待中~

你没有返回呀,所以旧的就不变了,一会我给你写代码

studentList.clear();

接收返回刷新后的list就行了,


     public static void main(String[] args) {
        Student s = new Student(123,"asd",123,"asd");
        Student s1 = new Student(123,"asd",123,"asd");
        Student s2 = new Student(123,"asd",123,"asd");
        Student s3 = new Student(123,"asd",123,"asd");
        ArrayList<Student> studentList = new ArrayList<>();
        Scanner sc = new Scanner(System.in);
        studentList.add(s);
        studentList.add(s1);
        studentList.add(s2);
        studentList.add(s3);

        System.out.println("======================");
        for (int i = 0; i < studentList.size(); i++) {
            System.out.println(studentList.get(i));
        }
        System.out.println("======================");

        studentList=flush(studentList, sc);

        System.out.println("======================");

        for (int i = 0; i < studentList.size(); i++) {
            System.out.println(studentList.get(i));
        }
    }

    private static ArrayList<Student> flush(ArrayList<Student> studentList, Scanner sc) {
        System.out.println("Ensure Flush? Y / N");
        String yn = sc.next();
        if (yn.equalsIgnoreCase("Y")) {
            ArrayList<Student> newStudentArrayList = new ArrayList<>();
            studentList = newStudentArrayList;
        }
        return studentList;
    }