« Return to Thread: List.contains problem
Rick Fincher wrote:Hi Jimmy,
This does not work because testOpt and MyOpt[0] are two different
objects, even though their labels and values are the same. If your code
was the following it would work:
Option testOpt = new Option("R2", "R2");
Option[] myOpt = new Option[]{
testOpt,
new Option("L22", "L2")
};
The equals(0 method compares pointers to the object. For Strings this works because Strings are immutable values and only one copy of a String containing the same characters is stored in memory.
If you do code like this:
String s1="hello";
String s2="hello";
Only one copy of the String "hello" is stored in memory with both s1 and s2 pointing to it. If you do this later:
s2="goodby";
A new String "goodby" is created and s2 is set to point to it, unless "goodby" was already in memory, then s2 would be set to point to the pre-existing String "goodby".
Because of that the String method equals() will work in situations like this.
That's one of the reasons String methods are slow in Java. Every time you change it a new String is created and the old one is left for garbage collection.
Manipulating StringBuffers is much faster and more memory efficient.
Rick
Jimmy200012 wrote:
> Hi, need some help to understand why this won't work:
>
> import com.sun.webui.jsf.model.Option;
> import java.util.*;
>
> public class ArrayListContains {
>
> /** Create a new instance of ArrayListContains */
> public ArrayListContains() {
> }
>
> public static void main(String[] args) {
> // Now the real test;
> Option[] myOpt = new Option[]{
> new Option("R2", "R2"),
> new Option("L22", "L2")
> };
>
> Option testOpt = new Option("R2", "R2");
>
> ArrayList<Option> optList = new
> ArrayList<Option>(Arrays.asList(myOpt));
> if (optList.contains(testOpt)) {
>
> // YOU THOUGHT WOULD PRINT THIS, BUT NOT.
> // com.sun.webui.jsf.model.Option DID NOT IMPLEMENTS EQUALS?
> // WHERE CAN I FIND SOME DOC ABOUT THIS?
> System.out.println("Yes!!!!!!!!!!!!R2");
> } else {
> System.out.println("why?????????????");
> }
> }
> }
>
---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@visualweb.netbeans.org
For additional commands, e-mail: users-help@visualweb.netbeans.org
« Return to Thread: List.contains problem
| Free Forum Powered by Nabble | Forum Help |