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?

Jonathan Lam
  • 15,294
  • 14
  • 60
  • 85
MED.HACEN
  • 19
  • 1
  • 6
  • 1
    See http://stackoverflow.com/questions/985229/search-in-java-arraylist for solutions (basically you'll need to walk the whole list with a "for" looking for a match). – John Hascall Dec 31 '15 at 21:24
  • Override the equals method in your class. – Atri Dec 31 '15 at 21:25

1 Answers1

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.

Community
  • 1
  • 1
ThisaruG
  • 2,382
  • 5
  • 34
  • 50
  • 1
    Using a foreach loop like `for (Train t : trainList) { ... t.getVilleDepart() ... }` is more elegant... – John Hascall Dec 31 '15 at 21:39
  • Thanks. I'll update this. – ThisaruG Dec 31 '15 at 21:40
  • thinks brothers but i to write a method which returns a list of trains: like this: public List getTrains(String villeDepart, String villeArrivee){} how can i do this with an arrayList – MED.HACEN Jan 01 '16 at 13:49
  • 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. – ThisaruG Jan 03 '16 at 18:46