-2

I'm building a small application (for fun) to basically track employees and products in a java app. I have created the arraylists and the classes but I'm having trouble sorting through them and searching.. Here is what I have tried so far..

I'm trying to search the objects of the arraylist based off of employee name

System.out.println("Enter name of employee to search: \n");
String name = keyboard.nextLine();
Iterator itr = employeeList.iterator();

while (itr.hasNext()) {
    Employee test = (Employee) itr.next();

    if (test.getFirstName() == name.toString()) {
    System.out.println(test.getEmpInfo());

    }
}  

My dilema is that if I replace the name.toString() with the name in quotes it works, but if I use the keyboard.nextLine() it won't work, any help would be greatly appreciated!

Tyler H
  • 89
  • 2
  • 12

1 Answers1

0

This is most common problem in java beginners. Use equals() method instead of == to compare Strings with java. So modify your code as follows.

if (test.getFirstName().equals(name.toString())) {
     //your code
}

NOTE: == is used to compare binary equality, which compares the memory location of objects. But .equals() is possible to override and it compares the value of objects according to specified logic.

Channa Jayamuni
  • 1,876
  • 1
  • 18
  • 29
  • Thanks! I did this and it worked... is there a more efficient way? ' if (test.getFirstName().equals(name.toString())) { System.out.println(test.getEmpInfo()); }' – Tyler H Oct 09 '15 at 21:07
  • yes, that's the only method you can use. sometimes you may no need to `name.toString()` if name is a String value. – Channa Jayamuni Oct 09 '15 at 21:09
  • True, there is no scenario in this case where it could be a string, but I have been trying to ensure that I handle all possible errors and doing best practice but you raise a good point.. thanks for the help! – Tyler H Oct 09 '15 at 21:11
  • 1
    @TylerH You could use a `foreach`, which is usually faster than a `while` or `for` when using `ArrayList`s. You could also use a stream filter, which should be the most efficient way to do this: `employeeList.stream().filter(anEmployee -> anEmployee.getFirstName().equals(name)).forEach(anEmployee -> System.out.println(anEmployee.getEmpInfo()));` I wrote a little example on pastebin: http://pastebin.com/qhLS5Y1B – showp1984 Oct 09 '15 at 21:11