Reputation: 3712
noticed the neat features of ruby symbols here
Does java have anything similar to this? what would it be called?
D don't think a final string would do all the features. especially the way its stored and it would still need a toString for comparison.
Upvotes: 1
Views: 1773
Reputation: 5712
The closest thing you can get to a Ruby Symbol in Java would be calling intern()
on a String.
While in Java you can have many String objects with the same content, intern
ensures that it returns the same object for the same content (sequence of characters), thus it returns a canonical/distinct value.
So, while for generic Java Strings you have to call the equals
method to check for content equality, for interned Strings you can simply use the ==
operator.
For further details, see: https://en.wikipedia.org/wiki/String_interning
Upvotes: 0
Reputation: 6180
Symbols are actually immutable identifiers. They can't change, are not garbage collected, and have performance advantages over Strings. I assume you already know what a String is. So the answer would be: Java doesn't have anything like Symbols.
Like @Idan said (and that is pretty clever) enums can be used as symbols except they don't have methods that you can call on. And symbols in Ruby are not immutable strings.
Refer to this post if you want to know their core differences.
Upvotes: 5
Reputation: 9
A Ruby symbol is an immutable string object which gets indexed in a symbol table for singe-reference re-use (hence the very inventive nomenclature!).
In Java, all String
objects are immutable, and all of them are indexed in the (inventively named) symbol table for re-use by the JVM (as long as they are referenced and live).
So, in Java, a String
("my_symbol"
) is the equivalent of a Ruby symbol (:my_symbol
).
To get something equivalent to a Ruby 'my string'
(non-immutable), you'd have to go to more complex Java classes (new StringBuilder("my string")
, etc.). Or, if you have Groovy loaded the JVM, it overlays a similar mutable concept with GString.
Upvotes: 1
Reputation: 5636
A symbol in ruby is just an immutable string. The java equivalent would just be a normal String
. I don't really see too many ruby specific features there, except maybe this memory leak one...
Upvotes: -4