CSC/ECE 517 Summer 2008/wiki1 6 c9): Difference between revisions
Line 25: | Line 25: | ||
====Adding elements to an array==== | ====Adding elements to an array==== | ||
'''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 | |||
Revision as of 14:55, 2 June 2008
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 provide efficient access to array elements, while hashes provide flexibility.
Array in Java and Ruby
Ruby - 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.
Java - An array is an indexed collection of items of same data type. 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 - The square bracket indicates the array declaration. 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
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
in Ruby -
Ruby does not require to declare the size of an array.
x = ['cat' , 5 ,6 ,'fly'] y = ['apple' , 'orange', 'pineapple']
An array can be declared with the new keyword also. for ex:
num = array.new
num << 3
num << 4
Now that array num has two element 3 and 4.
The indexing of an array starts from 0 and goes up to the size-1. Ruby supports the negative indexing in array.Negative index counts backward and x[-1] is same as referencing the last element of x.
Adding elements in the existing array
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 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:-
num = [1 ,2 ,4, 3, 5] num + ["apple", "cycle"] num =>[1, 2, 4 , 3,"5", "apple", "cycle"]
Another way to add the element is :-
num.push "berry"
It adds the berry at last in the array.
num =>[1, 2, 4 , 3,5,"Berry"]
Adding an element at a particular index is
num[index number] = item or num.insert(2,7)
num =>[1, 2,7,4,3,5]
The size of the array can be increased multiple times with the same element in the same order.
num = [1 ,2 , 3, 4, 5] num * 2 =>[1, 2, 3, 4, 5, 1, 2, 3, 4, 5] num * 3 =>[1, 2, 3, 4, 5, 1, 2, 3, 4, 5,1, 2, 3 ,4, 5]
Passing an array as a argument in a method:-
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. For ex: -
integer company (integer []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.
Ruby also 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(*args) puts #{args.join(",")} end hello('jon' ,'Mary') #=> jon,Mary
Deletion of an element from an array:-
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. 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.
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 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] num .delete_at(2) #=> [1, 2,4 ,5]
Some useful functionality with array:-
num = [1,2,3,4,5]
In Java to find the length of an array we can use an inbuilt function num.length => 5 and to sort the array ,reverse the array etc we have to write the algorthim depending on the requirement.
Ruby comes up with lots of easy built in methods that makes array very easy to use. For ex:-
num = [1 ,2 , 3, 4, 5,"apple"]
checks if array is empty : -
num.empty # =>true (if empty) false otherwise
size of an array :- num.size # =>6 (the size of an array)
type of the element:- num[0].size # =>fixnum
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"])
accesing array element num.at[0] # =>1
removes all elements from array num.clear # =>[]
reverse the array num.reverse #=> ["apple", 5, 4, 3, 2, 1]
return the index of an element num.rindex("b") #=> nil
num.rindex("2") #=> 2
sorting an array (x = [2, 4 3]) x.sort #=>[2, 3, 4]
Two dimensional array:-
In two dimensional array an array is arranged in the form of table with rows and columns.The array can be declared as :-
integer employee = new integer[4][5]; where number of rows are 4 and number of coloums are 5.
The array can be initialise as :-
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:-
num = [ [1, 2], [3, 4] ] num [0][0] -> 1 num [0][1] -> 2
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'. It is similar to array except hashes don't use numeric indices, 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. The keys must be unique, the values may be duplicated.
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
In Java - In order to initialize an hash we first need to create an empty HashMap. It can be done as follows -
Map food_color = new HashMap();
or
HashMap food_color = new HashMap();
In Ruby - There is no need to initialize the variables in Ruby. It can be simply done as follows -
food_color={}
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.
In Java -
Map food_color = new HashMap(); food_color.put( "Apple", "red" ); food_color.put( "Banana", "yellow" ); food_color.put( "Lemon", "yellow" ); food_color.put( "Carrot", "orange" );
or
HashMap food_color = new HashMap(); food_color.put( "Apple", "red" ); food_color.put( "Banana", "yellow" ); food_color.put( "Lemon", "yellow" ); food_color.put( "Carrot", "orange" );
In Ruby -
food_color = [ {'Fruit' => 'Apple', 'Color' => 'red}, {'Fruit' => 'Banana', 'Color' => 'yellow'}, {'Fruit' => 'Lemon', 'Color' => 'yellow'}, {'Fruit' => 'Carrot', 'Color' => 'orange'} ]
Another way of declaration is:-
food_color = {”Apple” => "red", “Banana” =>"yellow", “Lemon” =>"yellow", “Carrot” =>"orange"}
or
food_color = {”apple” , "red", “Banana”, "yellow", “Lemon” , "yellow", “Carrot”, "orange"}
or
food_color = {} # create an empty hash food_color["Apples"]="red" food_color["Banana"]="yellow" food_color["Lemon"]="yellow" food_color["Carrot"]="orange"
Adding an element to Hash
In Java - To add an element to hash in Java we need to use '.puts' method.
Map map = new HashMap(); Object key = null; Object value = null; map.put( key, value ); food_color.put( "Strawberry", "red" );
In 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.
food_color["Strawberry"]="red"
To print the whole hash
In Ruby -
food_color.each {|key, value| puts "#{key} => #{value}"}
In Java -
for ( Iterator it = food_color.keySet().iterator(); it.hasNext(); ) { System.out.println( it.next() );
}
Deleting an element from the Hash
In Ruby -
food_color.delete("Banana")
In Java -
food_color.remove( "Banana" );
To acces single element:-
fruits["apple"] => sweet
To sort an hash:-
In Ruby -
fruits.sort.each {|key, value| puts "#{key} => #{value}"}
=> apple=>sweet =>orange=>sweet and sour =>strawberry=>delicious
Hash allows the functionality of adding the numbers in the exixting key value.
num["x"] = 2 num["x"] +1 = 1 => 3
If the key-value does not exist and value is added it returns nil.For ex:- num["y"] += 3 =>return nil