Dynamic Arrays: Ruby vs Java.

Luke Glayat
Jul 30, 2017 · 4 min read

About two months ago, I made the decision to attend a programming boot camp where the first module in the curriculum has a large emphasis on learning to program in Ruby. Most, if not all, of my previous experience with programming has been with Java, so immediately the differences between the two languages became apparent to me. Most of these differences lead me to understand why Ruby is such a great fit for many peoples first programming language. The main reason is the fact that Ruby abstracts many things away from the programmer which, in most of cases make things so much easier to learn without getting hampered up with the fine details. On paper, the differences between the two languages are numerous e.g. Strongly Typed vs Weakly Typed, Compiled vs Interpreted, or the need of having various keywords such as public or static ubiquitously throughout your code. But for now, I would like to focus on how Ruby lets users interact with the Array class to maintain and manipulate lists.

Java Instantiation of Arrays:

String[] stringArr = new String[10];int[] integerArr = new int[10];Object[] objArr = new Object[10];

Ruby Instantiation of Arrays:

arr = []

The difference of even instantiating the Array class is quite obvious. In the above ‘stringArr’ and ‘integerArr’ arrays I have made are limited in the fact that they only take in one data type. However, the ‘objArr’ array I created is the most similar to the ruby variant, as they both take in Objects which may be of any type. The Ruby language does not bother the programmer with any of these specifics. This means a programmer using Ruby can get going using arrays with much more ease than someone using Java.

Let’s see what happens when we add 1000 elements to an array and print them out in Java and then in Ruby.

Java:

Input:int[] integerArr = new int[10];  // instantiate test arrayfor(int i = 0; i < 1000; i++){     integerArr[i] = i+1;     //populate test array}for(int i = 0; i < 1000; i++){    System.out.println(integerArr[i]);  //print out test array}Output: 
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10

Ruby:

Input:arr = [] # create array for testingval = 1 # counter used for testing1000.times do      arr << val #populate the array     val += 1endarr.each do |value|      puts value #print out elements of arrayendOutput: 1
2
.
.
1000

So the Java array threw an error but the Ruby one worked perfectly. Why is this?

When we initialize an empty array in any language, contiguous blocks of memory are reserved for the array. The computer does not know beforehand how many elements we are ultimately going to need to add into the list, and in some cases neither does the programmer.

Empty Array Visualization

In Java, the arrays have to be instantiated with a default size, so the programmer has to be specific when instantiating arrays. But how can this array be used dynamically in which it can resize to the programmers needs? Well the answer lies in the Java utils package, named the ArrayList class, which conveniently solves our dynamic programming needs in Java. This ArrayList class is actually the answer to why our Ruby array worked interestingly enough as well. Quite simply, because arrays in Ruby act very similarly to ArrayLists!

Taking a look at the Java documentation for ArrayLists, one can see that everything is quite similar to a regular Array class, except for a couple of extra methods tacked on to add the extra functionality that we need. Namely the methods are grow() and shrink(). The grow method is called in cases when an object is added to the array via the add() method. A quick check is made to see if there is room for the object in the Array, and if there isn’t we ask our Array to grow in size to make room and then we add the object. The new implementation in of the add method Java is listed below as well as the new grow method.

public void add( AnyType t) {    if ( size >= capacity ) //check to see if there is room        grow();             //if there isn't call the grow method    array[size]=t;          //then add element to array    size++;                 //increment size counter}
private void grow() {
Object[] newArr = new Object[capacity * 2];
//create new bigger array
for ( int i=0; i<array.length; i++ ) { newArr[i] = array[i]; //put elements into new array } array = newArr; //set old array to be the newer one}

The aforementioned shrink method works in a similar way when removing elements to make for a space efficient array in your computers memory, however less frequently used. Arrays in Ruby are over allocated memory so the resizing issue does not happen very frequently, but when its limits have almost exceeded, reallocation to a new array has become the de facto method for solving this problem.

That right there is how arrays dynamically resize in many programming languages and is just one of the small things that makes things simpler for us without us even knowing it. When it comes to Java and you have the choice between the two classes (arrays and ArrayLists), it is important to keep in mind that an array will suffice when the programmer knows exactly how many elements will be needed to store into an array. Using an ArrayList in certain situations may even be memory overkill. It never hurts to know what tools you have at hand though.

Ruby even takes arrays a step further by implementing extra methods in attempts to make an array a jack of all trades data structure. With methods pop() and push() functioning like a stack and push() and shift() functioning like a queue. When it comes to ease of use, but not necessarily the most precision, most definitely have an edge over Java.

Luke Glayat

Written by

Software Developer/Consultant

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade