0

I'm stuck at a part when I have to create a list and select something in it.

I have an executable

public class Executable{
    public static void main(String [] args){
        WeekEnd we = new WeekEnd();

        Personne pierre = new Personne("Pierrot");
        Personne anna = new Personne("anna");

        we.addPersonne(pierre);
        we.addPersonne(anna);

        System.out.println("test : "+we.findUsingEnhancedForLoop("anna"));

    }
}

I have my class Personne

public class Personne{
    private String name;

    public Personne(String name){
    this.name=name;
    }

    public String getPersonne(){
    return this.name;
    }
}

And my class WeekEnd where i try to select the name anna

import java.util.List;
import java.util.ArrayList;

public class WeekEnd{
    private ArrayList<Personne> listePersonne;

    public WeekEnd(){
      this.listePersonne = new ArrayList<>();
    }

   public Personne findUsingEnhancedForLoop(
   String name, ArrayList<Personne> listePersonne) {

      for (Personne personne : listePersonne) {
         if (personne.getPersonne().equals(name)) {
              return personne;
         }
     }
     return null;
   }

   public void addPersonne(Personne personne){
      listePersonne.add(personne);
   }
 }
14

2 Answers 2

2

The WeekEnd class already has a listePersonne member. You shouldn't pass such an argument, which will just hide this member:

public Personne findUsingEnhancedForLoop(String name) {
    // Rest of the code, as you had it...

Note, by the way, that using Java 8's streams can clean up the method's implementation considerably:

return
listePersonne.stream().filter(p -> p.getPersonne().equals(name)).findFirst().orElse(null);
Sign up to request clarification or add additional context in comments.

Comments

0

Firstly you shouldn't pass ArrayList<Personne> listePersonne as a parameter in Weekend class. Instead of this you can pass only String name as a parameter.

public Personne findUsingEnhancedForLoop(String name) {

  for (Personne personne : listePersonne) {
     if (personne.getPersonne().equals(name)) {
          return personne;
     }
 }
 return null;
}

Also findUsingEnhancedForLoop method returns a Personne object. If you want to print a Personne's name in System.out.println() you have to override toString() method inPersonne class from Object class.

    @Override
    public String toString() {
        return this.name;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.