The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

LinkedList of String

(Not sure if this belongs in OOP section...)
I have a LinkedList of String that I need to add to if something doesn't already exist, does the contains() function automatically do this? I guess I'm just really confused about the concept of object variables in this case because from what I understand object variables only "point" to a location in memory where the actual object is stored so if I had

Re: LinkedList of String

The value of object variables is a reference to an object. So you are right: a==b may well be false even though a.equals(b) is true. "the same" is not the same as "equal". Think of two $10 notes: they are, to all intents and purposes, equal, but the fact that there are two of them means they are not the same. Spend one and you have not, thereby, spent the other.

(Strings are a little strange because it turns out that string literals like "asdf" are the same as well as being equal. You should try the code you posted to see what System.out.println(a==b) really does print.)

-----

If I understand you correctly you want to add a string to a list but only if the list does not contain a string equal to the one you are thinking of adding. Have you looked at the API docs for contains()? Ask if it does not make sense. Try using it and post code if it does not do what you expect or intend.

Re: LinkedList of String

Because, as I said, string literals are special and == will be true if they contain the same characters. See 3.10.5. String Literals in the Java Language Specification where a more exact specification is given (and illustrated with an example) of when two string references will compare true with ==.

In general, however, equals() and == yield different results and you decide which you mean when you make a list of unique objects.