【问题标题】:Is there a way to update a record in an Arraylist without deleting the existing record?有没有办法在不删除现有记录的情况下更新 Arraylist 中的记录?
【发布时间】:2013-05-02 12:00:27
【问题描述】:

我有一个 arraylist ,其中记录存储为对象。我想知道是否有办法在不删除现有记录的情况下更新数组列表中的记录?

例如,我的记录具有名字、姓氏、姓名缩写、id 等属性。有没有办法更新记录中的名字,而不必同时提供所有其他属性值?

目前我所做的是当用户给出一个 id 时,我会查找该 id 是否与数组中的任何记录匹配,如果匹配,我将其从数组中删除并让用户从头开始输入所有详细信息.

【问题讨论】:

  • 我不认为它是否会工作,但你试一试..你可以使用 array.get(index) 来获取对象,然后使用更改它的名称并将其存储在相同的索引

标签: java arraylist record updates


【解决方案1】:

Arraylist 存储引用并且不复制/创建新对象。如果更改存储的对象引用,它也会反映在 arrayList 中。下面是一个示例代码来证明:

package arraylistExample;

import java.util.ArrayList;

/**
 * Class represeting entity to be stored in Arraylist 
 * 
 */
class Person {

private String name;
private int age;
private String address;

public Person(String name, int age, String address) {
    super();
    this.name = name;
    this.age = age;
    this.address = address;
}

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 getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address;
}

@Override
public String toString() {
    return "Person [name=" + name + ", age=" + age + ", address=" + address
            + "]";
}


}

.

/**
 * Public class to run the demo
 *
 */
public class ArraylistObjectModify {

public static void main(String args[]) {

    // Add an arraylist and add elements to it
    ArrayList<Person> personList = new ArrayList<Person>();
    personList.add(new Person("Juned",32,"Bangalore"));
    personList.add(new Person("Ahsan",31,"Delhi"));
    personList.add(new Person("Sniper",1,"Grave"));

    //Print list elements before change
    System.out.println("Arraylist pre objects modification");
    System.out.println("----------------------------------");
    for(Person person:personList) {
        System.out.println(person);
    }

    for(Person person:personList) {
        if(person.getName().equals("Juned")) {
            person.setName("ChangedJuned");
            person.setAddress("Hola-lulu");
        }
    }

    //Print list elements after change
    System.out.println("Arraylist post objects modification");
    System.out.println("----------------------------------");
    for(Person person:personList) {
        System.out.println(person);
    }


}

}

【讨论】:

    【解决方案2】:

    如果您的记录是一个对象,其中包含可变字段(getter 和 setter),例如名称...通过某个标识符查找对象,然后使用新值调用 setter 来替换旧值。

    【讨论】:

      【解决方案3】:

      使用 set() 方法。

      表单 Java API 文档:

      set
      public E set(int index,
                   E element)
      Replaces the element at the specified position in this list with the specified element.
      

      取自here

      【讨论】:

        【解决方案4】:

        如果你想更新一两个值,你可以使用 setter。如果您知道当前对象的索引,那么您可以将新对象添加到该索引 例如:- Arraylist.add(index, element) 这将更新现有元素。

        【讨论】:

          【解决方案5】:

          您的对象应该包含一种设置/获取其属性的方法,可以是直接访问它们,也可以通过 set/get 方法。

          例如

          ArrayList<YourObject> Records = new ArrayList<YourObject>();
          
          //Loop through your ArrayList and check if their ID attribute matches
          for(YourObject record : Records) {
              if(record.id == userGivenID) {
                  //prompt the user to change whichever values you want 
                  Scanner s = new Scanner(System.in);
                  System.out.print("Change the name of this record > ");
                  record.setName(s.nextLine());
                  ...etc...
              }
          }
          

          最好使用 get/set 方法,例如

          record.setName("Bob");
          String name = record.getName();
          

          【讨论】:

            【解决方案6】:
            // Check this example
            
            public class Test {
                public static void main(String[] args){
                    List<Student> al = new ArrayList<Student>();
            
                    Student s1 = new Student(1, "John", "Nash", "N");
                    Student s2 = new Student(2, "John", "Slash", "s");
            
                    al.add(s1);
                    al.add(s2);
            
            
                    for(Student s:al){
                        if(s.getId() == 2){
                            s.setfNmae("Nks");
                            al.add(al.indexOf(s), s);
                        }
                       s.display();
                    }
            
                }
            }
            
            class Student{
                private int id;
                private String fName;
                private String lName;
                private String initial;
            
                Student(int id, String fName, String lName, String initial){
                    this.id = id;
                    this.fName = fName;
                    this.lName = lName;
                    this.initial = initial;
                }
                void display(){
                    System.out.println(id);
                    System.out.println(fName);
                    System.out.println(lName);
                    System.out.println(initial);
                }
            
                /**
                 * @return the id
                 */
                public int getId() {
                    return id;
                }
            
                /**
                 * @param id the id to set
                 */
                public void setId(int id) {
                    this.id = id;
                }
            
                /**
                 * @return the fNmae
                 */
                public String getfNmae() {
                    return fName;
                }
            
                /**
                 * @param fNmae the fNmae to set
                 */
                public void setfNmae(String fNmae) {
                    this.fName = fNmae;
                }
            
                /**
                 * @return the lName
                 */
                public String getlName() {
                    return lName;
                }
            
                /**
                 * @param lName the lName to set
                 */
                public void setlName(String lName) {
                    this.lName = lName;
                }
            
                /**
                 * @return the initial
                 */
                public String getInitial() {
                    return initial;
                }
            
                /**
                 * @param initial the initial to set
                 */
                public void setInitial(String initial) {
                    this.initial = initial;
                }
            }
            

            【讨论】:

            • 谢谢,我使用 get/set 方法让它工作了。谢谢大家。
            猜你喜欢
            • 2014-07-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-06-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多