If Statment Help
Can anyone tell me why the if statement never passes please. I have put the lines that are shown in the terminal window under the code. (the System.out.println() )
The bottom two System.out's are just a test to see if they are changing and they do but the if statement doesn't see they are the same.
Terminal window shows this:
int listPosition = 0;
while(listPosition < basket.size())
item = basket.get(listPosition);
if(itemName.toLowerCase() == item.getName().toLowerCase())
System.out.println(itemName + " Removed");
So they are the same and the toLowerCase is working but for some reason the if statement doesn't see them as the same, why is this?
Strings cannot be reliable compared using equality. Object equality compares the pointer, not the value, so if you do "A" == "A", then that is successful; however, if you do
new String("A") == new String("A") that will not be successful as they are two distinct objects.
Use .equals or .equalsIgnoreCase to perform a comparison of string objects.
I changed it to.equalsIgnoreCase() but this throws and error at me.
Can you modify my code so its right please.
if(itemName.equalsIgnoreCase() == item.getName().equalsIgnoreCase())
Nevermind I figured out how to do it.
You betcha. Keep doing as many object comparisons as you can using the .equals method, and you're good to go. Use the comparison operators primarily for primitives or when you actually want to compare objects for identical check. Equals is defined from the core object, so you can easily override and define your own handling.
Two interfaces to look at as well are the Comparable interface which will grant you the
int compareTo(T); method, and the Comparator interface which will grant you the
int compare(T, T); method. These can both be used for equality check, as the result of the "same" object would be 0 in either of these, but are also useful for using Collections as the sorting algorithms will make use of the Comparator, or you can usually provide the sort with a Comparator.