我有一个组件类:
public class Components {
int numberOfNets;
String nameOfComp;
String nameOfCompPart;
int numOfPin;
public components(int i, String compName, String partName, int pin) {
this.numberOfNets = i;
this.nameOfComp = compName;
this.nameOfCompPart = partName;
this.numOfPin = pin;
}
}
Run Code Online (Sandbox Code Playgroud)
在另一个类中,我创建了一个 Components 类的数组列表:
List<Components> compList = new ArrayList<Components>();
Run Code Online (Sandbox Code Playgroud)
稍后在代码中,我以这种方式添加 List 中的元素:
compList.add(new Components(0,compName,partName,0));
Run Code Online (Sandbox Code Playgroud)
请参阅此处,numberOfNetsComponentsnumOfPin类中的变量以 0 值启动。但是这些值在代码的后面部分中进行计算/递增,因此我需要更新每个列表元素中这两个变量的新值。现在,从ArrayList 文档中,我得到了通过操作使用索引来更新列表元素的想法set。但我很困惑如何在类的 ArrayList 中设置/更新类的特定变量。我只需要更新这两个提到的变量,而不是 Components 类中的所有四个变量。有什么办法可以做到这一点吗?
小智 5
您应该将 getter/setter 添加到组件类中,以便外部类可以更新组件的成员
public class Components {
private int numberOfNets;
private String nameOfComp;
private String nameOfCompPart;
private int numOfPin;
public components(int i, String compName, String partName, int pin) {
setNumberOfNets(i);
setNameOfComp(compName);
setNameOfCompPart(partName);
setNumOfPin(pin);
}
public void setNumberOfNets(int numberOfNets) {
this.numberOfNets = numberOfNets;
}
// Similarly other getter and setters
}
Run Code Online (Sandbox Code Playgroud)
您现在可以使用以下代码修改任何数据,因为 get() 将返回对原始对象的引用,因此修改此对象将在 ArrayList 中更新
compList.get(0).setNumberOfNets(newNumberOfNets);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2054 次 |
| 最近记录: |