如何调用ArrayList中动态创建的Adherent类实例并修改属性?
解决方案
首先明确:你完全不需要给每个Adherent实例单独起不同的变量名,ArrayList的核心作用就是帮你管理数量不确定的对象实例,通过列表本身就能获取到任意实例并调用它们的set/get方法。
先优化你的createAdherent方法
你当前代码里有冗余操作:创建Adherent对象时已经把lastName、firstName等参数传给构造函数了,之后又重复调用set方法赋值,这完全没必要。假设你的Adherent构造函数已经正确初始化这些属性,那代码可以简化成这样:
public static List<Adherent> createAdherent(int currentId, int currentYear, List<Adherent> adherentList) { Scanner sc = new Scanner(System.in); System.out.println("Please enter the last name of the new adherent"); String lastName = sc.next(); System.out.println("Please enter the first name of the new adherent"); String firstName = sc.next(); // 构造函数直接初始化属性,无需后续重复set Adherent adherent = new Adherent(lastName, firstName, currentYear, currentId); adherentList.add(adherent); System.out.println(adherent.toString()); return adherentList; }
如何调用实例的set/get方法
你可以通过两种方式从ArrayList中获取实例并修改:
1. 通过索引获取(知道实例在列表中的位置)
比如要修改第3个添加的Adherent的ID(注意列表索引从0开始):
// 获取列表中索引为2的实例(第3个) Adherent targetAdherent = adherentList.get(2); // 修改ID targetAdherent.setId(newId);
2. 通过属性查找(不知道位置,根据实例的特征匹配)
比如要修改某个姓名为"Smith"的Adherent的ID,可以遍历列表查找:
String targetLastName = "Smith"; int newId = 1005; for (Adherent adherent : adherentList) { if (targetLastName.equals(adherent.getLastName())) { adherent.setId(newId); // 如果只需要修改第一个匹配的,找到后可以break break; } }
关于“给每个实例赋予不同名称”的误区
代码里的变量名(比如你用的adherent)只是当前方法内的局部引用,当方法执行完,这个局部变量就会被销毁,但实例本身还存在于ArrayList中。你不需要给每个实例单独命名,因为ArrayList已经保存了所有实例的引用,通过列表就能访问到它们——就像你用一个盒子装了一堆东西,不需要给每个东西贴单独的标签,只要知道怎么从盒子里找到它就行。
内容的提问来源于stack exchange,提问作者Tungstenn
相关产品推荐
相关产品推荐

