0

I have an ArrayList which contains a list of Trains:

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;
    }
}

I want to search the ArrayList by villeDepart and villeArrivee. How can I do this?

2

1 Answer 1

2

As I can think of, you have to use a loop and go through whole list.

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
  }
}

EDIT:

As @Atri mentioned, you can Override your equals method. It's much easier. In your Train class,

@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;
  }
}

Read This Question in SO.

Sign up to request clarification or add additional context in comments.

4 Comments

Using a foreach loop like for (Train t : trainList) { ... t.getVilleDepart() ... } is more elegant...
Thanks. I'll update this.
thinks brothers but i to write a method which returns a list of trains: like this: public List <Train> getTrains(String villeDepart, String villeArrivee){} how can i do this with an arrayList
As I mentioned in my code //You got your train - you can do whatever you want. Create an ArrayList in the beginning of your method (before for each loop), then add your train into the newly created ~ArrayList`. Return it later.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.