![]() |
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. Code:
int listPosition = 0;Code:
ErrorThanks Ash |
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.
Code:
if(itemName.equalsIgnoreCase() == item.getName().equalsIgnoreCase())Thanks Ash |
Nevermind I figured out how to do it.
Thanks anyway. |
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. |
| All times are GMT +1. The time now is 04:57 PM. |
Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.