CSC/ECE 517 Summer 2008/wiki1 6 c9): Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
 
(176 intermediate revisions by 3 users not shown)
Line 1: Line 1:
Array in Java:-
'''''Problem Definition''' - Arrays and hashes are built into Ruby. Arrays, of course, are built into Java too, but hashes are only available through library classes. Compare Ruby and Java arrays, as well as hashes. Write equivalent code sequences in the two languages that illustrate the convenience of programming these constructs in both languages.
Arrays are built in.
''
An array is an indexed collection of items of same data type.We are not allowed to declare an array consist of multiple data type(like double and integer in same array).
=Arrays and Hashes=


Arrays in Ruby :-
[http://en.wikipedia.org/wiki/Array Arrays] and [http://en.wikipedia.org/wiki/Hash_function hashes] are indexed collection of objects, that are accessible using a key. In arrays, the 'key' is called as an 'index', and it is always an integer. In hashes, the 'key' can be an object of any type.Arrays and hashes provides lots of methods that makes it more flexible to use.Arrays and hashes can be sorted,the assigned values can be changed, and it can be passed as a argument in functions like a variable. Most of the programming languages are limited to store the same data type so the array occupies a contiguous area of storage.
Arrays are the indexed collection of objects in Ruby, which is accessible using keys.The key is always an integer in a an array and the array can grow as needed.Ruby support to store different type of data to store in one array.An array can can have integer, floating point number or a string.


Declaration of array in Java:-
Arrays provide efficient access to array elements, while hashes provide flexibility.Searching the elements are easy in hashes as compared to array but still array is powerful because hashes can not be ordered that easily like arrays because it is not ordered numerically. Hashes return the default value in the case of accessing the key value that do not exist in hash.


integer [] employee;
==== Arrays====
double employee[];
===== Values stored in array =====
'''[http://www.ruby-lang.org/en/ Ruby]''' - An array is used to store a list of objects in one object. Ruby support storing different  data types in one array, it is ''heterogeneous''. An array can can have integer, floating point number or a string.


The square bracket indicates the array declaration.
'''[http://java.sun.com/ Java]''' - An array is an indexed collection of items of same data type. It is used to store a list of data in one variable. Java cannot hold multiple data types, like double,integer, strings, etc.  in the same array.


It can also be declared in one line as :-
===== Declaration of array =====
'''Ruby''' - It is not necessary to declare the size of an array, in Ruby.
employee = ['David', 5 ,6 ,'Mary']
An array can also be declared with the keyword 'new'. For example -
employee = array.new


  integer employee = new integer [5];
'''Java''' - An array is declared by a set of square brackets[]. In the following example, 'employee' is an array of integers. There are different ways of declaring an array. Some of them are described below -
  '''1.''' String[] employee;
'''2.''' String employee[];
'''3.''' String employee = new String[5];   // 5 indicates the size of the array
Unless we have initialized the array at the time of declaration we need to specify the size of an array before using it.
The indexing of an array starts from 0 to size-1.It means if the array is of size 5 then first element is stored at employee[0] and the last one is at employee[4] .In an array the elements can be initialized one by one until the previously declared size of an array is reached.


Now the Employee array has allocated the memory to store the five integers.Unless we have initialised the array at the time of  
'''4.''' String [] employee = {Jack, Mary, David, Thomas}; // the size of an array is 4.
declaration we need to specify the size of an array before using it.
If elements are initialized at the time of the declaration then their is  no need of specifying a size to an array.The size of an array is same as the number of initialized elements.


The indexing of an array starts from 0 to size-1.It means if the array is of size 5 then first element is stored at employee[0]  
===== Adding elements to an array=====
and the last one is at employee[4] .In an array the elements can be initialised one by one upto the previously declared size of an array.
'''Ruby''' -
We can add elements to the array as follows -
employee = ['Jack', 'Mary', 'David', 'Thomas']
or to add elements to an array that is declared with the keyword 'new' -
employee << "Mary"
employee << "John"
or
employee[0] = "Mary"
employee[1] = "Jack"
Now the array employee has two elements Mary and John.


for ex:-
employee = %w[Jack Mary David Thomas]
        String employee = new String [5]
This is another way of declaring array of string.
        for(int i = 0; i <5 ; i++)
        {
          employee[i] = i;
        }


If elements are initialised at the time of the declaration then ther is  no need of specifying a size to an array.The size of an array is  
'''''Indexing'''''-
same as the number of initialised elements. for ex:-
The indexing of an array starts from 0 and goes up to the sizeOfArray-1. Ruby supports the negative indexing in array. Negative index
counts backward and employee[-1] is same as referencing the last element of employee.


String [] weekday = {Monday,Tuesday,wednesday,Thursday,friday,Saturday,Sunday};
'''Java -''' We can add elements to the 'employee' array of size 5, as follows -
for(int i = 0; i <5 ; i++)
{
    employee[i] = i;
}
or we can simply add the elements to the array at the time of declaration
String [] employee = {Jack, Mary, David, Thomas};


In this example the size of an array is 7.
'''''Indexing''''' -
The indexing of an array starts from 0 and goes up to the sizeOfArray-1, however, it does not support negative indexing like Ruby.


===== Adding elements in the existing array  =====


Declaration of array in Ruby:-  
'''Ruby -''' Arrays in Ruby are dynamic. It is very flexible with adding the number of elements in the array at run time, since ruby is not bound to declare the size of an array before using it. For ex:-


Ruby does not require to declare the size of an array.
  employee = [1 ,2 ,4, 3, 5]
x = ['cat' , 5 ,6 ,'fly']
  employee + ["apple", "cycle"]
y = ['apple' , 'orange', 'pineapple']
  employee =>[1, 2, 4 , 3,"5", "apple", "cycle"]


An array can be declared with the new keyword also. for ex:
Another way to add the element is :-
  employee = [1 ,2 ,4, 3, 5]
  employee.push "berry"
  employee =>[1, 2, 4 , 3,5,"Berry"]


num = array.new


num << 3
An element can be added at a particular index in following ways-
  employee = [1 ,2 ,4, 3, 5]
  employee[2] = 7
  employee =>[1, 2,7,4,3,5]


num << 4
  employee = [1 ,2 ,4, 3, 5]
  employee.insert(2,7)
  employee =>[1, 2,7,4,3,5]


Now that array num has two element 3 and 4.
The size of the array can be increased multiple times with the same element in the same order.
  employee = [1 ,2 , 3, 4, 5]
  employee * 2 =>[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
  employee * 3 =>[1, 2, 3, 4, 5, 1, 2, 3, 4, 5,1, 2, 3 ,4, 5]


The indexing of an array starts from 0 and goes up to the size-1. Ruby supports the negative indexing in array.Negative index
'''Java -'''
counts backward and x[-1] is same as referencing the last element of x.
Java does not allow to add more elements than the size of an existing array. If user is interested to add more elements to the array ,the size of the array needs to be increased accordingly.


===== Print the whole array =====
'''Ruby-'''In ruby we can print the array in following ways:-
employee  = [1,2,3,4,5]
employee
=> [1,2,3,4,5]
or
puts employee =>
1
2
3
4
5
or
employee.to_s =>"12345"
or
employee.each {|e| puts e }=>
1
2
3
4
5


'''Java-'''In Java the array can be printed as follows:
  Integer employee = new Integer[5];
for(int i = 0 ; i< 5 ;i++)
{
  system.out.println (employee[i]);
}


Adding elements in the existing array :-
===== Passing an array as a argument in a method =====


Java does not allow to add more elements than the size of an existing array.If user is interested to add more items,the size of the array needs to be increased.
'''Ruby-'''Ruby provide the functionality of passing an array as a argument in methods.  
Ruby is very flexible with adding the number of elements in the array at run time of any data type since ruby is not bound to declare the size of an array before using it.For ex:-
The argument name in the declaration of the method starts with the "*" symbol indicates that the argument is an array.  


num = [1 ,2 ,4, 3, 5]
def hello(*employee)
puts #{employee.join(",")}
end
hello('john' ,'Mary')  #=> jon,Mary


num + ["apple", "cycle"]
'''Java-'''Java also support to pass an array as an argument like a variable is passed to a method with some additional rules.
For ex: -
      void company (String []employee)
        {
        return 0;       
        }
        company(employee);


num =>[1, 2, 4 , 3,"5", "apple", "cycle"]
When an array is passed to a method only the reference of the array  is passed the
copy of the array is not created in the method.


Another way to add the element is :-
===== Deletion of an element from an array =====


num.push "berry"
'''Ruby-''' In ruby deleting an element from an array is very easy as compared to Java.The adjustment of elements
are done automatically.If an element is removed from an 'j'th position then the elements from the position j+1 moves one position down.
For ex:-
num = [1, 2, 3, 4, 5]
num.delete(3)            #=> [1 ,2 ,3, 5]
num .delete_at(2)        #=> [1, 2,4 ,5]


It adds the berry at last in the array.
'''Java-''' In Java Deletion requires some kind of search to locate to particular item in the array.There are two ways to remove an element from an array. The first approach is to reset the array element to null but this can cause holes in the array.The second approach is to store the real occurrence at the beginning of the array and null references can be kept at the end of the array.
The second approach comes up with two possible solutions.If the jth element is removed then the element starting from the j+1th position to the null will be shifted one position lower.And the second possibility is to replace the removed null reference with the last reference of an array.This technique can be used only if array is not arranged in a particular order otherwise the first possibility  is suitable to use.


num =>[1, 2, 4 , 3,5,"Berry"]
===== Some useful functionality with array:- =====


Adding an element at a particular index is num[index number] = item
'''Ruby-''' Ruby comes up with lots of easy  built in methods that makes array very easy to use [http://www.techotopia.com/index.php/Understanding_Ruby_Arrays].For ex:-
num = [1 ,2 , 3, 4, 5,"apple"]
num.empty    # =>true (if empty) false otherwise
size of an array :-                      num.size                # =>6 (the size of an array)
type of the element:-                    num[5].class  #=>string
first element of the array:-            num.first        # =>1
last element of the array :-            num.last          #=>apple
Adding an element :-                    num.push "orange"      # =>[1 ,2 , 3,4,5,"apple","orange"]
removing the last element                num.pop                # =>[1 ,2 , 3, 4, 5,"apple"])
accessing array element                  num.at[0]  # =>1
removes all elements from array          num.clear              # =>[]
reverse the array                        num.reverse          #=> ["apple", 5, 4, 3, 2, 1]
sorting an array  (x = [2, 4 3])        x.sort                  #=>[2, 3, 4]
return the index of an element         num.rindex("b")  #=> nil
from an array         num.rindex("2")        #=> 2


or num.insert(2,7)
'''Java-''' In Java to find the length of an array we can use an inbuilt function
num  = [1,2,3,4,5]
num.length => 5
and to sort the array ,reverse the array etc we have to write the algorthim depending on the requirement.


num =>[1, 2,7,4,3,5]
===== Two dimensional array =====


The size of the array can be increased multiple times with the same element in the same order.
'''Ruby-''' Ruby does not support two dimensional array but still the same effect can be generated through nested array:-
num = [1 ,2 , 3, 4, 5]


num * 2 =>[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
num = [ [1, 2], [3, 4] ]
num [0][0] -> 1
num [0][1] -> 2


num *3 =>[1, 2, 3, 4, 5, 1, 2, 3, 4, 5,1, 2, 3 ,4, 5]
However, Ruby has an excellent library in the Ruby Application Archive called NArray (by Masahiro Tanaka) to implement multi dimensional array of data type integers.


'''Java-''' In two dimensional array an array is arranged in the form of table with rows and columns.The array can be declared as :-


Passing an array as a argument in a method:-
int matrix = new int[4][5];
where number of rows are 4 and number of columns are 5.


In Java an array can be passed to a method as an argument like a variable is passed to a method with some additional rules.
The array can be initialize in a following way :-
For ex: -
         for(int i = 0; i<4 ; i++)
         integer company (integer []employee)
         {
         {
        return 0;      
              for(int j = 0; j<5 ; j++)
              {
                  matrix[i][j] = 1;
              }
         }
         }
        company(employee);
or


When an array is passed to a method only the reference of the array is passed the
  String[][] employee=
copy of the array is not created in the method.
{
  {"Mary","John","Sam","Soni"},
  {"Ron","Tod","Ria","Rachel"},
};


Ruby also provide the functionality of passing an array as a argument in methods.
==== Hashes ====
The argument name in the declaration of the method starts with the "*" symbol indicates that the argument is an array.


def hello(*args)
===== Hashing in Ruby and Java =====


puts #{args.join(",")}
A collection of key value pair is called 'hash'. It is sometimes called as 'associative array' or 'dictionaries' or a 'paired group of elements' in simpler terms. The objects that the keys refer to are called values. Keys and values occur in pairs, so there must be an even number of arguments. The keys must be unique, the values may be duplicated. It is similar to array except that the keys are not necessarily integers and may not always follow some specific sequence. Also, hashes don't use numeric indices, the word keys are used instead.


end
===== Language Support =====


hello('jon' ,'Mary')  #=> jon,Mary
'''In Ruby''' - Hashes are built-in objects in Ruby.


'''In Java''' - Java does not provide direct support for implementing hashes. We need to import Java's API named 'Java.util.*' in order to implement hashes.


Deletion of an element from an array:-
===== Declaration of hash=====


In Java Deletion requires some kind of search to locate to particular item in the array.There are two ways to remove an element from an array. The first approach is to reset the array element to null but this can cause holes in the array.The second approach is to store the real occurence at the begining of the array and null refernces can be kept at the end of the array.
'''Ruby''' - There is no need to initialize the variables in Ruby. It can be simply done as follows -
The second approach comes up with two possible solutions.If the jth element is removed then the element starting from the j+1th position to the null will be shifted one position lower.And the second possibility is to replace the removed null refernce with the last refernece of an array.This technique can be used only if array is not arranged in aparticular order otherwise the first possibility is suitable to use.
  veg_type={}


In ruby deleting an element from an array is very easy as compared to Java.The adjustment of elements
'''Java''' - In Java, hash can be implemented using 'Map' interface. It can also be implemented using java.util.HashMap, java.util.Hashtable, java.util.LinkedHashMap and java.util.TreeMap. We will consider [http://java.sun.com/j2se/1.4.2/docs/api/java/util/HashMap.html HashMap] implementation as it facilitates easy insertion, deletion, and retrieval of elements.
are done automatically.If an element is removed from an jth position then the elements from the position j+1 moves one position down.
For ex:-
num = [1, 2, 3, 4, 5]


num.delete(3)             #=> [1 ,2 ,3, 5]
In order to initialize a hash we first need to create an empty HashMap. It can be done as follows -
Map veg_type = new HashMap();
or
HashMap veg_type = new HashMap();


num .delete_at(2)        #=> [1, 2,4 ,5]
===== Initialization of hash =====
If we want to map the fruits with their respective colors, we can do that by defining hashes. The following paragraphs will show the difference in initialization using Java and Ruby.


'''Ruby -'''
veg_type = [ 
    {'Veg' => 'Tomato', 'Color' => 'red}, 
    {'Veg' => 'Squash', 'Color' => 'yellow'},     
    {'Veg' => 'Lemon', 'Color' => 'yellow'}
    ] 


Some useful functionality with array:-
Another way of declaration is:-
 
veg_type = {”Tomato” => "red", “Squash” =>"yellow", “Lemon” =>"yellow"}
num = [1,2,3,4,5]
or
 
  veg_type = {”Tomato” , "red", “squash”, "yellow", “Lemon” , "yellow"}
In Java to find the length of an array we can use an inbuilt function num.length => 5
or
and to sort the array ,reverse the array etc we have to write the algorthim depending on the requirment.
veg_type = {}    # create an empty hash
 
veg_type["Tomato"]="red"
Ruby comes up with lots of easy built in methods that makes array very easy to use.
veg_type["squash"]="yellow"
For ex:-
  veg_type["Lemon"]="yellow"
   
   
num = [1 ,2 , 3, 4, 5,"apple"]


checks if array is empty : -   num.empty    # =>true (if empty) false otherwise
'''Java -'''
HashMap  veg_type = new HashMap();
      veg_type.put( "Tomato", "red" );
      veg_type.put( "Squash", "yellow" );
      veg_type.put( "Lemon", "yellow" );
or the same can be implemented using Map as a return type.


size of an array :-                     num.size                # =>6 (the size of an array)
===== Type of elements in Hash =====
'''Ruby''' - Ruby is a pure object oriented language, everything is considered as an object. Therefore, any object can be added as an element to Ruby. For example, if we want to add food price as an value to hash food_market, we have to do it as follows -
food_market = {}    # create an empty hash
food_market["Apples"]=2
food_market["Banana"]=1
food_market["Strawberry"]=4


type of the element:-                    num[0].size    # =>fixnum
'''Java''' - Hashes in Java do not support primitive data types as it is a type of generic data structure. In order to add a primitive data type like int in a hash we need to represent it as an object.  
HashMap food_market = new HashMap();
food_market.put( "Apple", new Integer( 2 ) );
food_market.put( "Banana", new Integer( 1 ) );
food_market.put( "Strawberry", new Integer( 4 ) );


                                        num[5].class  #=>string
===== Adding an element to Hash =====


first element of the array:-             num.first        # =>1
'''Ruby''' - In Ruby, we can add element to hash just like array except the difference that the index is an object and doesn't have to be integer.
  veg_type["Peas"]="green"
output:-
{”Tomato” , "red", “squash”, "yellow", “Lemon” , "yellow" , "Peas" ,"green"}


last element of the array :-            num.last          #=>apple
'''Java''' - To add an element to hash in Java we need to use 'puts' method.
  veg_type.put( "Peas", "green" );


Adding an element :-                     num.push "orange"       # =>[1 ,2 , 3, 4,5,"apple","orange"]
===== To print the whole  hash =====
'''Ruby''' -  
    veg_type.each {|key, value| puts "#{key} => #{value}"
output:-
    Tomato => red 
    Squash => yellow
    Lemon  => yellow


removing the last element                num.pop                # =>[1 ,2 , 3, 4, 5,"apple"])
'''Java''' -


accesing array element                  num.at[0]   # =>1
Set set =  veg_type.entrySet();  //[http://java.sun.com/j2se/1.4.2/docs/api/java/util/Map.html#entrySet() entrySet()] is used to set the view of mappings in the hash.
Iterator i = set.Iterator();
while((i.hasNext()))
    {
      Map.Entry me = (Map.Entry)i.next();
      System.out.println(me.getKey() + " => " me.getValue());
    }


removes all elements from array          num.clear              # =>[]
===== Deleting an element from the Hash =====
The following examples will delete an element 'Banana' in the hash in Ruby and Java.


reverse the array                        num.reverse          #=> ["apple", 5, 4, 3, 2, 1]
'''Ruby''' -
  veg_type.delete("Squash")
output:-
  {”Tomato” , "red", “Lemon” , "yellow"}


return the index of an element         num.rindex("b") #=> nil
'''Java''' -
  veg_type.remove( "squash" );


                num.rindex("2")        #=> 2
===== To sort the elements of the hash =====


sorting an array  (x = [2, 4 3])        x.sort                 #=>[2, 3, 4]
'''Ruby''' -
In Ruby, the method sort is defined on the class 'Hash'. Hence it is very simple to sort elements in hash. The following code will sort and print the hash.
  veg_type.sort.each {|key, value| puts "#{key} => #{value}"} 
output:-
  Lemon  => yellow
  Squash => yellow
  Tomato => red 
   
 
'''Java - '''
In Java, in order to sort elements, we dump the HashMap into the [http://java.sun.com/j2se/1.4.2/docs/api/java/util/TreeMap.html TreeMap()]. TreeMap constructs a new hash, containing the same elements as the given hash, which is sorted according to the keys in natural order. We can simply pass the hash as an argument.
  Map  veg_type_sorted = new TreeMap( veg_type);


===== Passing the hash as a argument in a method =====


Two dimensional array:-
'''Ruby - '''The hash can be passed as a argument in methods in ruby.
 
 
In two dimensional array an array is arranged in the form of table with rows and coloumns.The array can be declared as :-
Definition of a method :-
 
def veg_type(params)
integer employee = new integer[4][5];
puts(params[:Tomato]) => "red"
where number of rows are 4 and number of coloums are 5.
puts(params[:Squash]) => "yellow"
 
puts(params[:lemon]=> "yellow"
The array can be initialise as :-
end
        for(int i = 0; i<4 ; i++)
        {
              for(int j = 0; j<5 ; j++)
              {
                  employee[i][j] = 1;
                      }
                }


Ruby does not support two dimensional array but still the same effect can be generated through nested array:-  
Method is called as :-  
veg_type(:Tomato => "red",:Squash => "yellow",:Lemon => "yellow")


num = [ [1, 2], [3, 4] ]
Output:-
num [0][0] -> 1
"red"
num [0][1] -> 2
"yellow"
"yellow"


'''Java-'''


Definition of a method:-
function veg_type(params)
{
system.out.println (params.Tomato);
system.out.println (params.Squash);
system.out.println (params.Lemon);
}


Method is called as:-
veg_type({Tomato : "red", Squash : “Yellow”, Lemon: "yellow});


Hashing in ruby and Java:-
output:-
"red"
"yellow"
"yellow"


==Reference==
[http://en.wikipedia.org/wiki/Array More about Arrays]


[http://en.wikipedia.org/wiki/Hash_function More about Hashes]


A collection of key value pair is called hash.It is similar to array except hashes don't use numeric indices,
[http://www.ruby-lang.org/en/ Ruby Homepage]
the word keys are used instead. The objects that the keys refer to are called values.Keys and values
occur in pairs, so there must be an even number of arguments.


In Ruby,  variables must be initialised,  the content of a variable that doesn't exist  return the nil.
[http:///www.sun.java.com Java Homepage]


[http://highered.mcgraw-hill.com/sites/0072518847/information_center_view0/ An introduction to Object-Oriented Programming with Java, Chapter 10]


Decalaration and initialisation of hash:-
[http://www.ruby-doc.org/docs/ProgrammingRuby/ Programming Ruby ,the Pragmatic Programmers Guide]


cities = [
[http://www.troubleshooters.com/codecorn/ruby/basictutorial.htm#_Arrays Arrays in Basic Ruby Tutorial]
    {"Name" => "Raleigh", "State" => "NC"}, 
    {"Name" => "los angeles", "State" => "CA"},     
    {"Name" => "miami", "State" => "FL"} 
    ]


Another way of declaration is:-
[http://www.rubyist.net/~slagell/ruby/arrays.html Adding elements to an array]
fruits = {”apple” => "sweet", “strawberry” =>"delicious",“orange” =>"sweet and sour"}
fruits= {”apple” , "sweet", “strawberry” ,"delicious",“orange” ,"sweet and sour"}


To print the whole  hash:-
[http://www.techotopia.com/index.php/Understanding_Ruby_Arrays Adding and accessing the array element]


  fruits.each {|key, value| puts "#{key} => #{value}"} 
[http://www.techotopia.com/index.php/Understanding_Ruby_Arrays More functionality of arrays in Ruby]
=> apple=>sweet
=> strawberry=>delicious
=> orange=>sweet and sour


To acces single element:-
[http://www.troubleshooters.com/codecorn/ruby/basictutorial.htm#_Hashes Hashes in Basic Ruby Tutorial]


fruits["apple"] => sweet
[http://www.math.umd.edu/~dcarrera/ruby/0.3/chp_03/hashes.html Learning Hashes in Ruby]


To sort an hash:-
[http://www.rubyfleebie.com/an-introduction-to-hashes/ Hashing in Ruby]


fruits.sort.each {|key, value| puts "#{key} => #{value}"} 
[http://www.rubyfleebie.com/an-introduction-to-hashes/ Hashes and methods in Ruby]
=> apple=>sweet
=>orange=>sweet and sour
=>strawberry=>delicious


[http://www.javascriptkata.com/2007/03/22/how-to-use-anonymous-objects/ Hashes and methods in Java]


Hash allows the functionality of adding the numbers in the exixting key value.
[http://java.sun.com/j2se/1.4.2/docs/api/java/util/HashMap.html More about HashMaps in Java]


num["x"] = 2
[http://java.sun.com/j2se/1.4.2/docs/api/java/util/Map.html#entrySet() More about entrySet() in Java]
num["x"] +1 = 1
=> 3


If the key-value does not exist and value is added it returns nil.For ex:-
[http://java.sun.com/j2se/1.4.2/docs/api/java/util/TreeMap.html More about TreeMaps in Java]
num["y"] += 3
=>return nil

Latest revision as of 01:30, 12 June 2008

Problem Definition - Arrays and hashes are built into Ruby. Arrays, of course, are built into Java too, but hashes are only available through library classes. Compare Ruby and Java arrays, as well as hashes. Write equivalent code sequences in the two languages that illustrate the convenience of programming these constructs in both languages.

Arrays and Hashes

Arrays and hashes are indexed collection of objects, that are accessible using a key. In arrays, the 'key' is called as an 'index', and it is always an integer. In hashes, the 'key' can be an object of any type.Arrays and hashes provides lots of methods that makes it more flexible to use.Arrays and hashes can be sorted,the assigned values can be changed, and it can be passed as a argument in functions like a variable. Most of the programming languages are limited to store the same data type so the array occupies a contiguous area of storage.

Arrays provide efficient access to array elements, while hashes provide flexibility.Searching the elements are easy in hashes as compared to array but still array is powerful because hashes can not be ordered that easily like arrays because it is not ordered numerically. Hashes return the default value in the case of accessing the key value that do not exist in hash.

Arrays

Values stored in array

Ruby - An array is used to store a list of objects in one object. Ruby support storing different data types in one array, it is heterogeneous. An array can can have integer, floating point number or a string.

Java - An array is an indexed collection of items of same data type. It is used to store a list of data in one variable. Java cannot hold multiple data types, like double,integer, strings, etc. in the same array.

Declaration of array

Ruby - It is not necessary to declare the size of an array, in Ruby.

employee = ['David', 5 ,6 ,'Mary']

An array can also be declared with the keyword 'new'. For example -

employee = array.new

Java - An array is declared by a set of square brackets[]. In the following example, 'employee' is an array of integers. There are different ways of declaring an array. Some of them are described below -

1. String[] employee; 
2. String employee[];
3. String employee = new String[5];   // 5 indicates the size of the array

Unless we have initialized the array at the time of declaration we need to specify the size of an array before using it. The indexing of an array starts from 0 to size-1.It means if the array is of size 5 then first element is stored at employee[0] and the last one is at employee[4] .In an array the elements can be initialized one by one until the previously declared size of an array is reached.

4. String [] employee = {Jack, Mary, David, Thomas}; // the size of an array is 4.

If elements are initialized at the time of the declaration then their is no need of specifying a size to an array.The size of an array is same as the number of initialized elements.

Adding elements to an array

Ruby - We can add elements to the array as follows -

employee = ['Jack', 'Mary', 'David', 'Thomas']

or to add elements to an array that is declared with the keyword 'new' -

employee << "Mary"
employee << "John"

or

employee[0] = "Mary"
employee[1] = "Jack"

Now the array employee has two elements Mary and John.

employee = %w[Jack Mary David Thomas]

This is another way of declaring array of string.

Indexing- The indexing of an array starts from 0 and goes up to the sizeOfArray-1. Ruby supports the negative indexing in array. Negative index counts backward and employee[-1] is same as referencing the last element of employee.

Java - We can add elements to the 'employee' array of size 5, as follows -

for(int i = 0; i <5 ; i++)
{
   employee[i] = i;
} 

or we can simply add the elements to the array at the time of declaration

String [] employee = {Jack, Mary, David, Thomas};

Indexing - The indexing of an array starts from 0 and goes up to the sizeOfArray-1, however, it does not support negative indexing like Ruby.

Adding elements in the existing array

Ruby - Arrays in Ruby are dynamic. It is very flexible with adding the number of elements in the array at run time, since ruby is not bound to declare the size of an array before using it. For ex:-

 employee = [1 ,2 ,4, 3, 5]
 employee + ["apple", "cycle"]
 employee =>[1, 2, 4 , 3,"5", "apple", "cycle"]

Another way to add the element is :-

 employee = [1 ,2 ,4, 3, 5]
 employee.push "berry"
 employee =>[1, 2, 4 , 3,5,"Berry"]


An element can be added at a particular index in following ways-

 employee = [1 ,2 ,4, 3, 5]
 employee[2] = 7
 employee =>[1, 2,7,4,3,5]
 employee = [1 ,2 ,4, 3, 5]
 employee.insert(2,7)
 employee =>[1, 2,7,4,3,5]

The size of the array can be increased multiple times with the same element in the same order.

 employee = [1 ,2 , 3, 4, 5]
 employee * 2 =>[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
 employee * 3 =>[1, 2, 3, 4, 5, 1, 2, 3, 4, 5,1, 2, 3 ,4, 5]

Java - Java does not allow to add more elements than the size of an existing array. If user is interested to add more elements to the array ,the size of the array needs to be increased accordingly.

Print the whole array

Ruby-In ruby we can print the array in following ways:-

employee  = [1,2,3,4,5]
employee
=> [1,2,3,4,5] 

or

puts employee =>
1
2
3
4
5

or

employee.to_s =>"12345"

or

employee.each {|e| puts e }=>
1
2
3
4
5

Java-In Java the array can be printed as follows:

 Integer employee = new Integer[5];
for(int i = 0 ; i< 5 ;i++)
{
  system.out.println (employee[i]);
}
Passing an array as a argument in a method

Ruby-Ruby provide the functionality of passing an array as a argument in methods. The argument name in the declaration of the method starts with the "*" symbol indicates that the argument is an array.

def hello(*employee)
puts #{employee.join(",")}
end
hello('john' ,'Mary')   #=> jon,Mary

Java-Java also support to pass an array as an argument like a variable is passed to a method with some additional rules. For ex: -

     void company (String []employee)
       {
        return 0;        
       }
       company(employee);

When an array is passed to a method only the reference of the array is passed the copy of the array is not created in the method.

Deletion of an element from an array

Ruby- In ruby deleting an element from an array is very easy as compared to Java.The adjustment of elements are done automatically.If an element is removed from an 'j'th position then the elements from the position j+1 moves one position down. For ex:-

num = [1, 2, 3, 4, 5]
num.delete(3)            #=> [1 ,2 ,3, 5]
num .delete_at(2)        #=> [1, 2,4 ,5]

Java- In Java Deletion requires some kind of search to locate to particular item in the array.There are two ways to remove an element from an array. The first approach is to reset the array element to null but this can cause holes in the array.The second approach is to store the real occurrence at the beginning of the array and null references can be kept at the end of the array. The second approach comes up with two possible solutions.If the jth element is removed then the element starting from the j+1th position to the null will be shifted one position lower.And the second possibility is to replace the removed null reference with the last reference of an array.This technique can be used only if array is not arranged in a particular order otherwise the first possibility is suitable to use.

Some useful functionality with array:-

Ruby- Ruby comes up with lots of easy built in methods that makes array very easy to use [1].For ex:-

num = [1 ,2 , 3, 4, 5,"apple"]
num.empty     # =>true (if empty) false otherwise
size of an array :-                      num.size                # =>6 (the size of an array)
type of the element:-                    num[5].class   	 #=>string
first element of the array:-             num.first         	 # =>1
last element of the array :-             num.last           	 #=>apple
Adding an element :-                     num.push "orange"       # =>[1 ,2 , 3,4,5,"apple","orange"]
removing the last element                num.pop                 # =>[1 ,2 , 3, 4, 5,"apple"])
accessing array element                   num.at[0]   		 # =>1
removes all elements from array          num.clear               # =>[]
reverse the array                        num.reverse  	         #=> ["apple", 5, 4, 3, 2, 1]
sorting an array  (x = [2, 4 3])         x.sort                  #=>[2, 3, 4]
return the index of an element	         num.rindex("b")  	 #=> nil
from an array			         num.rindex("2")         #=> 2	

Java- In Java to find the length of an array we can use an inbuilt function

num  = [1,2,3,4,5]
num.length => 5

and to sort the array ,reverse the array etc we have to write the algorthim depending on the requirement.

Two dimensional array

Ruby- Ruby does not support two dimensional array but still the same effect can be generated through nested array:-

num = [ [1, 2], [3, 4] ]
num [0][0] -> 1
num [0][1] -> 2

However, Ruby has an excellent library in the Ruby Application Archive called NArray (by Masahiro Tanaka) to implement multi dimensional array of data type integers.

Java- In two dimensional array an array is arranged in the form of table with rows and columns.The array can be declared as :-

int matrix = new int[4][5]; where number of rows are 4 and number of columns are 5.

The array can be initialize in a following way :-

       for(int i = 0; i<4 ; i++)
       {
             for(int j = 0; j<5 ; j++)
             {
                 matrix[i][j] = 1;
             }
       }

or

String[][] employee= 
{ 
  {"Mary","John","Sam","Soni"}, 
  {"Ron","Tod","Ria","Rachel"}, 
};

Hashes

Hashing in Ruby and Java

A collection of key value pair is called 'hash'. It is sometimes called as 'associative array' or 'dictionaries' or a 'paired group of elements' in simpler terms. The objects that the keys refer to are called values. Keys and values occur in pairs, so there must be an even number of arguments. The keys must be unique, the values may be duplicated. It is similar to array except that the keys are not necessarily integers and may not always follow some specific sequence. Also, hashes don't use numeric indices, the word keys are used instead.

Language Support

In Ruby - Hashes are built-in objects in Ruby.

In Java - Java does not provide direct support for implementing hashes. We need to import Java's API named 'Java.util.*' in order to implement hashes.

Declaration of hash

Ruby - There is no need to initialize the variables in Ruby. It can be simply done as follows -

veg_type={}

Java - In Java, hash can be implemented using 'Map' interface. It can also be implemented using java.util.HashMap, java.util.Hashtable, java.util.LinkedHashMap and java.util.TreeMap. We will consider HashMap implementation as it facilitates easy insertion, deletion, and retrieval of elements.

In order to initialize a hash we first need to create an empty HashMap. It can be done as follows -

Map veg_type = new HashMap();

or

HashMap veg_type = new HashMap();
Initialization of hash

If we want to map the fruits with their respective colors, we can do that by defining hashes. The following paragraphs will show the difference in initialization using Java and Ruby.

Ruby -

veg_type = [  
   {'Veg' => 'Tomato', 'Color' => 'red},  
   {'Veg' => 'Squash', 'Color' => 'yellow'},      
   {'Veg' => 'Lemon', 'Color' => 'yellow'} 
   ]  

Another way of declaration is:-

veg_type = {”Tomato” => "red", “Squash” =>"yellow", “Lemon” =>"yellow"}

or

veg_type = {”Tomato” , "red", “squash”, "yellow", “Lemon” , "yellow"}

or

veg_type = {}    # create an empty hash
veg_type["Tomato"]="red"
veg_type["squash"]="yellow"
veg_type["Lemon"]="yellow"

Java -

HashMap  veg_type = new HashMap();
     veg_type.put( "Tomato", "red" );
     veg_type.put( "Squash", "yellow" );
     veg_type.put( "Lemon", "yellow" );

or the same can be implemented using Map as a return type.

Type of elements in Hash

Ruby - Ruby is a pure object oriented language, everything is considered as an object. Therefore, any object can be added as an element to Ruby. For example, if we want to add food price as an value to hash food_market, we have to do it as follows - food_market = {} # create an empty hash food_market["Apples"]=2 food_market["Banana"]=1 food_market["Strawberry"]=4

Java - Hashes in Java do not support primitive data types as it is a type of generic data structure. In order to add a primitive data type like int in a hash we need to represent it as an object. HashMap food_market = new HashMap();

food_market.put( "Apple", new Integer( 2 ) );
food_market.put( "Banana", new Integer( 1 ) );
food_market.put( "Strawberry", new Integer( 4 ) );
Adding an element to Hash

Ruby - In Ruby, we can add element to hash just like array except the difference that the index is an object and doesn't have to be integer.

 veg_type["Peas"]="green"

output:-

{”Tomato” , "red", “squash”, "yellow", “Lemon” , "yellow" , "Peas" ,"green"}

Java - To add an element to hash in Java we need to use 'puts' method.

 veg_type.put( "Peas", "green" );
To print the whole hash

Ruby -

   veg_type.each {|key, value| puts "#{key} => #{value}"}  

output:-

   Tomato => red  
   Squash => yellow
   Lemon  => yellow

Java -

Set set =  veg_type.entrySet();   //entrySet() is used to set the view of mappings in the hash. 
Iterator i = set.Iterator();
while((i.hasNext()))
   {
      Map.Entry me = (Map.Entry)i.next();
      System.out.println(me.getKey() + " => " me.getValue());
   }
Deleting an element from the Hash

The following examples will delete an element 'Banana' in the hash in Ruby and Java.

Ruby -

 veg_type.delete("Squash")

output:-

 {”Tomato” , "red", “Lemon” , "yellow"}

Java -

 veg_type.remove( "squash" );
To sort the elements of the hash

Ruby - In Ruby, the method sort is defined on the class 'Hash'. Hence it is very simple to sort elements in hash. The following code will sort and print the hash.

 veg_type.sort.each {|key, value| puts "#{key} => #{value}"}  

output:-

 Lemon  => yellow
 Squash => yellow
 Tomato => red  
   
 

Java - In Java, in order to sort elements, we dump the HashMap into the TreeMap(). TreeMap constructs a new hash, containing the same elements as the given hash, which is sorted according to the keys in natural order. We can simply pass the hash as an argument.

 Map  veg_type_sorted = new TreeMap( veg_type);
Passing the hash as a argument in a method

Ruby - The hash can be passed as a argument in methods in ruby.

Definition of a method :-

def veg_type(params)
puts(params[:Tomato]) => "red"
puts(params[:Squash]) => "yellow"
puts(params[:lemon])  => "yellow"
end

Method is called as :-

veg_type(:Tomato => "red",:Squash => "yellow",:Lemon => "yellow")

Output:-

"red"
"yellow"
"yellow"

Java-

Definition of a method:-

function veg_type(params)
{
system.out.println (params.Tomato);
system.out.println (params.Squash);
system.out.println (params.Lemon);
}

Method is called as:-

veg_type({Tomato : "red", Squash : “Yellow”, Lemon: "yellow});

output:-

"red"
"yellow"
"yellow"

Reference

More about Arrays

More about Hashes

Ruby Homepage

Java Homepage

An introduction to Object-Oriented Programming with Java, Chapter 10

Programming Ruby ,the Pragmatic Programmers Guide

Arrays in Basic Ruby Tutorial

Adding elements to an array

Adding and accessing the array element

More functionality of arrays in Ruby

Hashes in Basic Ruby Tutorial

Learning Hashes in Ruby

Hashing in Ruby

Hashes and methods in Ruby

Hashes and methods in Java

More about HashMaps in Java

More about entrySet() in Java

More about TreeMaps in Java