我有ArrayList
,其中包含Train
s:
package train;
public class Train {
private String nom;
private String villeDepart, villeArrivee;
public Train() {
super();
// TODO Auto-generated constructor stub
}
public Train(String nom, String villeDepart, String villeArrivee) {
super();
this.nom = nom;
this.villeDepart = villeDepart;
this.villeArrivee = villeArrivee;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getVilleDepart() {
return villeDepart;
}
public void setVilleDepart(String villeDepart) {
this.villeDepart = villeDepart;
}
public String getVilleArrivee() {
return villeArrivee;
}
public void setVilleArrivee(String villeArrivee) {
this.villeArrivee = villeArrivee;
}
}
我想通过ArrayList
和villeDepart
搜索villeArrivee
。我怎么能这样做?
答案 0 :(得分:2)
我可以想到,你必须使用循环并浏览整个列表。
for each (Train train in list) {
String villeDepart = train.getVilleDepart();
String villeArrivee = train.getVilleArrivee();
if (villeDepart.equals("String you want to match") && villeArrivee.equals("Next String to match") {
//You got your train
}
}
修改强>
正如@Atri所提到的,你可以覆盖你的equals方法。这更容易。
在Train
课程中
@Override
public boolean equals(Object obj) {
Train train = (Train) obj;
if (this.villeArrivee.equals(train.getVilleArrivee()) && this.villeDepart.equals(train.getVilleDepart())) {
return true;
} else {
return false;
}
}
在SO中阅读This Question。