This question already has an answer here:
List of items with same values

(1个答案)


3年前关闭。




大家好,我是Java初学者,我编写了以下Java代码,它看起来像这样:

import java.util.LinkedList;
import java.util.Scanner;

public class Main {

    public static void main(String[] args)
    {
        LinkedList <Student>  l1 = new LinkedList<Student>();

        Scanner sc = new Scanner(System.in);

        Student e1 = new Student();

        int i=0;
        int choice;
        String name;
        String cne;

        do
        {

            System.out.println("Student name "+i);

            name = sc.nextLine();
            e1.setName(name);


            System.out.println("Student CNE "+i);
            cne = sc.nextLine();
            e1.setCne(cne);

            System.out.println(e1);

            l1.add(e1);


            System.out.println("type 1 to continue, other to quit : ");

            choice = sc.nextInt();

            sc.nextLine();

            i++;

        }while( choice == 1 );


        for ( i=0 ; i < l1.size() ; i++)
        {

            System.out.println(l1.get(i));
        }



    }

}


例如,当我添加三个学生时:(banash,001)(victor,002)(lykke,003)

我得到这个结果:

lykke => 003
lykke => 003
lykke => 003


谁能告诉我问题出在哪里!

最佳答案

您需要在循环中初始化Student对象。当前e1只是一个对象,您正在循环中更新其值。并在列表中添加相同的对象

public class Main {
    public static void main(String[] args) {
        LinkedList <Student>  l1 = new LinkedList<Student>();
        Scanner sc = new Scanner(System.in);

        int i=0;
        int choice;
        String name;
        String cne;

        do {
            Student e1 = new Student();
            System.out.println("Student name "+i);

            name = sc.nextLine();
            e1.setName(name);

            System.out.println("Student CNE "+i);
            cne = sc.nextLine();
            e1.setCne(cne);

            System.out.println(e1);

            l1.add(e1);

            System.out.println("type 1 to continue, other to quit : ");
            choice = sc.nextInt();
            sc.nextLine();
            i++;
        }while( choice == 1 );


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

关于java - 为什么我的Java LinkedList被添加相同的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40051923/

10-12 03:43
查看更多