(identical? "foo" "foo") evaluates to true

34 views
Skip to first unread message

C. Arel

unread,
Feb 15, 2011, 5:46:31 AM2/15/11
to Clojure
Hi all,
I am watching the data structure videos and there it evaluates to
false.
Does this mean that only one object is created now? (Clojure update on
String objects?)

Kind Regards,
Can

B Smith-Mannschott

unread,
Feb 15, 2011, 9:40:15 AM2/15/11
to clo...@googlegroups.com

I think this is a distinction without a difference since Strings are
immutable and behave like a value with respect to equals and hashCode.
I suspect the behavior may depend on whether two uses of a given
string literal end up being compiled into the same class file or not.
(Each class file has its own constant space where string literals
occuring in that class are stored.)

// Ben

Armando Blancas

unread,
Feb 15, 2011, 10:34:48 AM2/15/11
to Clojure
For compilation and evaluation, yes. But not strings created at
rumtime like:
(def foo (str \f \o \o))

http://groups.google.com/group/clojure/browse_thread/thread/e43af17a0424b1cd

Stuart Sierra

unread,
Feb 15, 2011, 6:27:30 PM2/15/11
to clo...@googlegroups.com
Since about 1.1, I think, the Clojure compiler calls String.intern() on String literals.  So yes, they are the same object.

-Stuart Sierra

C. Arel

unread,
Feb 16, 2011, 3:33:43 AM2/16/11
to Clojure
Thank you all,
It has to be the same object otherwise it makes no sense. Anyways that
is good news since this means that Clojure has a little support built
in so you don't create unneccessary objects.

/Can Arel

Matthew Boston

unread,
Feb 17, 2011, 12:52:19 AM2/17/11
to Clojure
I think I recall something in a CS class about how String is (or
possibly is) implemented. Consider the following:

1) Each character of the alphabet, number, symbol etc. is assigned a
memory location. 0x00, 0x01, 0x02, etc. etc.
2) A String has an internal representation as a char[].

So, String s = "test" is really a char[] = ['t', 'e', 's', 't']

To represent this in memory, the char[] is really [0x20, 0x05, 0x19,
0x20] to represent each letter respectively. Now conside a new String
s2 = "test".

Again, this will have the same "path" of internal memory addresses.
Therefore (identical? "test" "test") is the same path of memory
addresses and is identical?.

Meikel Brandmeyer

unread,
Feb 17, 2011, 9:34:58 AM2/17/11
to Clojure
Hi,

On 17 Feb., 06:52, Matthew Boston <matthew.bos...@gmail.com> wrote:

> Again, this will have the same "path" of internal memory addresses.
> Therefore (identical? "test" "test") is the same path of memory
> addresses and is identical?.

This is the = way. identical? means you really have the same array.
Not only the same contents.

Sincerely
Meikel
Reply all
Reply to author
Forward
0 new messages