CSC/ECE 517 Summer 2008/wiki1 6 c9)

From Expertiza_Wiki
Jump to navigation Jump to search

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.

Arrays

Values stored in array

Ruby - An array is used to store a list of objects in one object. 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. 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 - Ruby 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 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]

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 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.

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"])
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]
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

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 employee = new int[4][5]; where number of rows are 4 and number of coloums 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++)
             {
                 employee[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 -

food_color={}

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 food_color = new HashMap();

or

HashMap food_color = 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 -

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"

Java -

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" );

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.

food_color["Strawberry"]="red"

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

food_color.put( "Strawberry", "red" );
To print the whole hash

Ruby -

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

Java -

Set set = food_color.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 -

food_color.delete("Banana")

Java -

food_color.remove( "Banana" );
To sort an 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.

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

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 food_color_sorted = new TreeMap(food_color);