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.

Neo.W
  • 19
  • 2
  • Do you need to use the `Iterator` explicitly, or is it enough if you use the [enhanced for-loop](https://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with) which uses `Iterator` internally? – Mick Mnemonic Jan 16 '16 at 03:41
  • What's the requirement for what you need to return when you don't find find a female? – entpnerd Jan 16 '16 at 05:08

3 Answers3

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;
Gaktan
  • 458
  • 3
  • 9
  • Its always suggested to use literals on the LHS for equals comparison like `"female".equals(p.getGender())` to avoid NullPointerException issue – Aaditya Gavandalkar Jan 16 '16 at 07:31
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(); }

Rameshwar Bhaskaran
  • 345
  • 1
  • 4
  • 16
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
user unknown
  • 35,537
  • 11
  • 75
  • 121
CMPS
  • 7,733
  • 4
  • 28
  • 53