Ruby Arrays and Java Lists21 Jun 2016
Let’s look at Java’s most used collection
java.util.ArrayList. Java, being
a static language, uses interfaces (to specify a common “quack-like” behavior for
objects) and array lists (conform) implement the
Unlike Java or other languages, Ruby does not have a separate array and list type,
Array acts like a mutable (unless
freeze happens) list of elements.
In fact, when a Ruby
Array is making it into a Java method it will do top-notch
when the parameter is of a list type (
RubyArray implements java.util.List).
Likewise, Java lists behave like Ruby’s array type, esp.
Compared to the list’s native
 method does not raise on out of
bounds and negative indexes and has all the functionality of an
The array-like behavior is added to the
java.util.List interface - acts as a module
in Ruby land. The above snippet thus works for any type (implementing the interface)
rindex fall-back to list iterators for non random access list,
compared to always looping using (ineffective)
get positioning previously.
The later example show how Java collections
dup very much like Ruby objects.
alias sort ruby_sort to handle the native
sort method added to lists
since Java 8. JRuby favors existing Java methods (they’re coming from the class while
sort is on the
java.util.List mixin), but provides a convention for dealing with
common ambiguities. Using the
ruby_sort name the Ruby-like manner might be brought in as needed.
Lastly, the Ruby
sort returns the same object type as its invoked on, which wasn’t
the case before JRuby 9.1.
Explaining ambiguities, the first example (literally) won’t work, since there’s
getFirst() instance method on
java.util.LinkedList which is recognized
as a getter (Java reader) and maps to
first() without any method parameters :