2

Here I got

public class Planet
{

    ArrayList<Person> person  = new ArrayList<>();
    Iterator<Person> itr = person.iterator();

    public String getFemaleName()
    {

        for (int a = 0;a < person.size();a++)
        {
            if (person.getGender == "female")
            {
                return person.get(a).getName();
            }
        }
    }
}

Now I'm having 2 problems, 1st is i just want return female's name,but it seems I have to return something even there is no female in my ArrayList. 2nd is how to use an Iterator instead of using a for loop.

2
  • Do you need to use the Iterator explicitly, or is it enough if you use the enhanced for-loop which uses Iterator internally? Commented Jan 16, 2016 at 3:41
  • What's the requirement for what you need to return when you don't find find a female? Commented Jan 16, 2016 at 5:08

3 Answers 3

1
  1. For the case when no female is present , simply putting a return null in the end of the function will do the job, because your first return statement won't be executed at all.

  2. For the second question, using an iterator .. just replace your for loop with

    while(itr.hasNext()) { Person newPerson=itr.next(); if(newPerson.getGender().equals("female") return newPerson.getName(); }

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

Comments

1
for (Person p : persons) // you should name your lists with plural
{
    if (p.getGender().equals("female")) // use .equals() to compare strings, since == works in weird ways
    {
        return p.getName();
    }
}
return null;

1 Comment

Its always suggested to use literals on the LHS for equals comparison like "female".equals(p.getGender()) to avoid NullPointerException issue
0

Advanced for loop:

for(Person person: persons)
   if(person.getGender.equals("female"))
      return person.getName();

return null;

Iterator:

Iterator<Person> personsIter = persons.iterator();
while (personsIter.hasNext()) {
    Person current = personIter.next(); 
    if(person.getGender.equals("female"))
       return person.getName();
}
return null

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.