CSC/ECE 517 Summer 2008/wiki1 6 c9): Difference between revisions
(→Arrays) |
|||
(123 intermediate revisions by 2 users not shown) | |||
Line 1: | Line 1: | ||
'''''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= | ||
[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 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. | |||
====Declaration of array ==== | ==== Arrays==== | ||
===== 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. | |||
'''[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. | |||
===== Declaration of array ===== | |||
'''Ruby''' - It is not necessary to declare the size of an array, in Ruby. | '''Ruby''' - It is not necessary to declare the size of an array, in Ruby. | ||
employee = ['David', 5 ,6 ,'Mary'] | employee = ['David', 5 ,6 ,'Mary'] | ||
Line 14: | Line 20: | ||
employee = array.new | employee = array.new | ||
'''Java''' - | '''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; | '''1.''' String[] employee; | ||
'''2.''' String employee[]; | '''2.''' String employee[]; | ||
Line 24: | Line 30: | ||
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. | 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==== | ===== Adding elements to an array===== | ||
'''Ruby''' - | |||
''' | |||
We can add elements to the array as follows - | We can add elements to the array as follows - | ||
employee = ['Jack', 'Mary', 'David', 'Thomas'] | employee = ['Jack', 'Mary', 'David', 'Thomas'] | ||
Line 44: | Line 42: | ||
employee[1] = "Jack" | employee[1] = "Jack" | ||
Now the array employee has two elements Mary and John. | Now the array employee has two elements Mary and John. | ||
The indexing of an array starts from 0 and goes up to the | |||
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. | 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 :- | 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: - | For ex: - | ||
void company (String []employee) | |||
{ | { | ||
return 0; | return 0; | ||
Line 87: | Line 140: | ||
When an array is passed to a method only the reference of the array is passed the | 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. | 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. | |||
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 | |||
For ex:- | For ex:- | ||
num = [1, 2, 3, 4, 5] | num = [1, 2, 3, 4, 5] | ||
num.delete(3) | num.delete(3) #=> [1 ,2 ,3, 5] | ||
num .delete_at(2) #=> [1, 2,4 ,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 [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 | |||
'''Java-''' In Java to find the length of an array we can use an inbuilt function | |||
num = [1,2,3,4,5] | 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 | |||
num = [1 ,2 , 3, 4 | |||
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 [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. | |||
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(); //[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()); | |||
} | |||
==== | ===== 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 ===== | ||
'''In Java''' | '''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 ===== | |||
'''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== | |||
[http://en.wikipedia.org/wiki/Array More about Arrays] | |||
[http://en.wikipedia.org/wiki/Hash_function More about Hashes] | |||
[http://www.ruby-lang.org/en/ Ruby Homepage] | |||
[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] | |||
[http://www.ruby-doc.org/docs/ProgrammingRuby/ Programming Ruby ,the Pragmatic Programmers Guide] | |||
[http://www.troubleshooters.com/codecorn/ruby/basictutorial.htm#_Arrays Arrays in Basic Ruby Tutorial] | |||
[http://www.rubyist.net/~slagell/ruby/arrays.html Adding elements to an array] | |||
[http://www.techotopia.com/index.php/Understanding_Ruby_Arrays Adding and accessing the array element] | |||
[http://www.techotopia.com/index.php/Understanding_Ruby_Arrays More functionality of arrays in Ruby] | |||
[http://www.troubleshooters.com/codecorn/ruby/basictutorial.htm#_Hashes Hashes in Basic Ruby Tutorial] | |||
[http://www.math.umd.edu/~dcarrera/ruby/0.3/chp_03/hashes.html Learning Hashes in Ruby] | |||
[http://www.rubyfleebie.com/an-introduction-to-hashes/ Hashing in Ruby] | |||
[http://www.rubyfleebie.com/an-introduction-to-hashes/ Hashes and methods in Ruby] | |||
[http://www.javascriptkata.com/2007/03/22/how-to-use-anonymous-objects/ Hashes and methods in Java] | |||
[http://java.sun.com/j2se/1.4.2/docs/api/java/util/HashMap.html More about HashMaps in Java] | |||
[http://java.sun.com/j2se/1.4.2/docs/api/java/util/Map.html#entrySet() More about entrySet() in Java] | |||
[http://java.sun.com/j2se/1.4.2/docs/api/java/util/TreeMap.html More about TreeMaps in Java] | |||
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
An introduction to Object-Oriented Programming with Java, Chapter 10
Programming Ruby ,the Pragmatic Programmers Guide
Adding and accessing the array element