JAVA:Arraylist会覆盖之前的条目

时间:2015-05-13 05:38:27

标签: java arrays arraylist

初学者,善待。

每当我通过“添加人”添加到arraylist时,它会覆盖前一个条目。因此,当我运行sort时,我会获得两个完全相同的条目,这些条目是最后输入的。我该如何解决?我该怎么办?

这是我的班级文件:

import java.util.Calendar;
import java.util.Date;
import java.text.*;

public class Person implements Comparable {

    private static int totalNumber;

    public static int getTotal() {

        // Returns total number of employees
        return totalNumber;
    }

    private String fName;
    private String lName;
    private Date lastModified;
    private String address;
    private String city;
    private String state;
    private String zip;
    private String phone;

    public Person(String fName, String lName, String address, String city,
            String state, String zip, String phone) {
        this.fName = fName;
        this.lName = lName;
        this.address = address;
        this.city = city;
        this.state = state;
        this.zip = zip;
        this.phone = phone;
        Calendar calobj = Calendar.getInstance();
        this.lastModified = calobj.getTime();
    }

    public String getfName() {
        return this.fName;
    }

    public void setfName(String fName) {
        this.fName = fName;
    }

    public String getlName() {
        return this.lName;
    }

    public void setlName(String lName) {
        this.lName = lName;
    }

    public Date getLastModified() {
        return this.lastModified;
    }

    public void setLastModified(Date lastModified) {
        this.lastModified = lastModified;
    }

    public String getAddress() {
        return this.address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCity() {
        return this.city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return this.state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getZip() {
        return this.zip;
    }

    public void setZip(String zip) {
        this.zip = zip;
    }

    public String getPhone() {
        return this.phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    @Override
    public String toString() {
        DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
        return "\n First Name= " + fName + "\n Last Name= " + lName
                + "\n Address= " + address + "\n City= " + city + "\n State= "
                + state + "\n Zip= " + zip + "\n Phone= " + phone
                + "\n Last Modified= " + df.format(lastModified);
    }

    @Override
    public int compareTo(Object other) {
        // TODO Auto-generated method stub
        return this.lName.compareToIgnoreCase(((Person) other).lName);

    }

}

这是我的测试文件:

import java.util.*;

public class testAddressBook {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        ArrayList<Person> addressBook = new ArrayList<Person>();
        Person newPerson = new Person(null, null, null, null, null, null, null);

        @SuppressWarnings("resource")
        Scanner sc = new Scanner(System.in);

        boolean switcher = true;
        do {
            System.out.println("\n\tAddress Book Menu");
            System.out.println("\n\t\tEnter A to (A)dd Person ");
            System.out.println("\t\tEnter D to (D)elete Person");
            System.out.println("\t\tEnter M to (M)odify Person");
            System.out.println("\t\tEnter S to (S)earch Address Book ");
            System.out.println("\t\tEnter L to (L)ist ALL (sorted) ");
            System.out.println("\t\tEnter Q to Quit");
            System.out.print("\n\tPlease enter your choice: ");
            char choice = sc.nextLine().toUpperCase().charAt(0);

            while ((choice != 'A') && (choice != 'D') && (choice != 'M')
                    && (choice != 'S') && (choice != 'L') && (choice != 'Q')) {
                System.out
                        .println("Invalid choice!  Please select (A)dd, (D)elete, (M)odify, (S)earch, (L)ist or (Q)uit: ");
                choice = sc.nextLine().toUpperCase().charAt(0);
            }

            switch (choice) {
            case 'A':
                System.out.println("\nTo add a person, follow the prompts.");

                System.out.print("\nEnter First Name: ");
                newPerson.setfName(sc.nextLine());

                System.out.print("\nEnter Last Name: ");
                newPerson.setlName(sc.nextLine());

                System.out.print("Enter Address: ");
                newPerson.setAddress(sc.nextLine());

                System.out.print("Enter City: ");
                newPerson.setCity(sc.nextLine());

                System.out.print("Enter State: ");
                newPerson.setState(sc.nextLine());

                System.out.print("Enter Zip: ");
                newPerson.setZip(sc.nextLine());

                System.out.print("Enter Phone Number: ");
                newPerson.setPhone(sc.nextLine());

                addressBook.add(newPerson);

                System.out
                        .println("\nYou have successfully added a new person!");

                break;

            case 'D':

                break;
            case 'M':

                break;
            case 'S':
                Collections.sort(addressBook);

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

                }
                System.out.println();

                break;
            case 'L':

                break;
            case 'Q':
                switcher = false;
                System.exit(0);
                break;
            default:

            }

        } while (switcher != false);

    }
}

5 个答案:

答案 0 :(得分:1)

您必须为循环的每次迭代创建Person的新实例。否则,您只是重新更新同一个人。

将此行移至do循环:

Person newPerson = new Person(null, null, null, null, null, null, null);

甚至更好,制作一个private方法,返回一个新的Person并具有类似

的方法
 addressBook.add(readNewPerson(sc));
 System.out.println("\nYou have successfully added a new person!");

答案 1 :(得分:1)

您只创建一次人员:

 Person newPerson = new Person(null, null, null, null, null, null, null);

并覆盖每个循环中的属性。您必须在循环中创建一个新人:

   do {
        System.out.println("\n\tAddress Book Menu");
        System.out.println("\n\t\tEnter A to (A)dd Person ");
        System.out.println("\t\tEnter D to (D)elete Person");
        System.out.println("\t\tEnter M to (M)odify Person");
        System.out.println("\t\tEnter S to (S)earch Address Book ");
        System.out.println("\t\tEnter L to (L)ist ALL (sorted) ");
        System.out.println("\t\tEnter Q to Quit");
        System.out.print("\n\tPlease enter your choice: ");
        char choice = sc.nextLine().toUpperCase().charAt(0);


        while ((choice != 'A') && (choice != 'D') && (choice != 'M')  && (choice != 'S') && (choice != 'L')&& (choice != 'Q')) {
            System.out.println("Invalid choice!  Please select (A)dd, (D)elete, (M)odify, (S)earch, (L)ist or (Q)uit: ");
            choice = sc.nextLine().toUpperCase().charAt(0);
        }


        switch (choice) {
        case 'A' :      
            System.out.println("\nTo add a person, follow the prompts.");       
            Person newPerson = new Person(null, null, null, null, null, null, null);
 ....

答案 2 :(得分:1)

您需要在循环中实例化一个新Person。例如声明:

Person newPerson;

然后在while循环实例化它:

switch (choice) {
        case 'A' :      
            System.out.println("\nTo add a person, follow the prompts.");       
            newPerson = new Person(null, null, null, null, null, null, null);
 .... so on

如果你也将它从循环中实例化,它会导致创建一个额外的对象。

答案 3 :(得分:0)

           `Person newPerson = new Person();//define a default constructor
             . . . . 
            System.out.print("Enter Phone Number: ");
            newPerson.setPhone(sc.nextLine());

            addressBook.add(newPerson);`

你需要在循环中创建一个新人并设置他的属性,最后将该人添加到列表中。

答案 4 :(得分:0)

您反复重复使用newPerson对象,只需重写内部字段。在Java中,对象(而不是原始)变量是对象的命名引用,因此每次执行addressBook.add(newPerson)时都要将相同的对象添加到列表中(这是允许的,因为它& #39;不是Set)。您newPerson复制到列表中,您只是将列表中的第n个位置指向newPerson

最小的改变是移动对象构造函数调用Thilo建议,但我非常同意他的进一步建议,即你应该为每个案例使用专用方法。在这种情况下,由于局部变量的范围,整个问题会整齐地消失。一般来说,你应该构建你的程序,使它们有意义并且可读(而不是单一的main程序),并且直接导致各种错误永远不会发生

另见:

What's the difference between passing by reference vs. passing by value?