CSC/ECE 517 Fall 2007/wiki1 1 aman: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
 
(67 intermediate revisions by the same user not shown)
Line 1: Line 1:
'''
'''
'''HashMaps in Java vs hashes in Ruby'''
'''HashMaps in Java vs Hashes in Ruby'''


Maps in java or hashes in ruby is any unordered object which stores associations between keys and their corresponding values, in which both keys and the values are objects. The key is unique , however the values may not necessarily be unique. The key, is used to retrieve a value from the map at a later stage after having had stored the values.
Maps in java or hashes in ruby is any unordered object which stores associations between keys and their corresponding values, in which both keys and the values are objects. The key is unique , however the values may not necessarily be unique. The key, is used to retrieve a value from the map at a later stage after having had stored the values.
Line 6: Line 6:
'''Comparing HashMaps and Hashes'''
'''Comparing HashMaps and Hashes'''


1.In version 1.5 of Java ,the generic feature of Java has implemented building type safe collections.In Ruby as well arrays or hashes can be made type safe by modifying ruby classes directly.
1. Both in Java and Ruby, data structures are treated as objects. Hence both HashMaps and Hashes are used to store and manipulate objects which can be instantiated using the new method.
  in Java using  : HashMap h = new HashMap;
  in Ruby using  : h = hash.new


'''Difference between Hashmaps and Hashes'''In Ruby there is no difference between primitive data types and objects.Hence any variable or object can be put directly into hashes container and methods can be invoked on them .However in Java primitive objects needs to be type casted to an Object class in order to use in built methods on arrays or hashmaps.
2. In Ruby there is no difference between primitive data types and objects.Hence any variable or object can be put directly into the hashes container and methods can be invoked on them. However in Java primitive objects needs to be type casted to an Object class in order to use in built methods on the created HashMaps.
 
3. Ruby has the same syntactic sugar for hashes as well as arrays which makes the implementing hashes as simple as implementing an array. In Java however, since HashMaps implement the Collections framework, objects have to be inserted using the put method.
  in Java using  : h.put (New Integer(0234), "Peter Drake");
  in Ruby using  : h = {0234 => "Peter Drake"} 


In Java for when
4. Inbuilt iterator feature of ruby enables accessing items one at a time. However in java, Hashmaps cannot implement the Iterator interface. To implement the iteration feature , a collection view of the map for example a Set needs to be used.
  in Java using  : Iterator itr = h.keySet().iterator();
  in Ruby using  : h.each_pair{|key,value| puts key,value, " "}


HashMap hm = new HashMap();
'''Sample Codes'''
hm.put(new Integer(10), new Integer(40));
In the above example we have used the java.lang framework for wrapping primitive type to Integer Objects.
The following sample codes  compares simplicity in implementing a HashMap in Java with Hashes in Ruby . The following codes creates a hashmap to associate names of people as keys with their ages as values. The code prints out the keys and values and also finds the average age of the group.  
In Ruby:
h=Hashes.new{10=>"40"}


2)Ruby has the same syntactic sugar for hashes as well as arrays which makes the implementing hashes as simple as implementing an array.
Java Code :  
Eg : h=Hash.new{"First"=>A,"Second"=>b,"third"=>c}


While in Java since they implement the collections framework so elements have to be inserted using add or put methods.
  package assgn1;
      hm.put("Betty Matthews", new Integer(40));
  import java.util.*;
3)Inbuilt iterator feature of ruby enables accessing items one at a time. However in java Hashmaps cannot implement the Iterator interface. To implement the iteration feature , a collection view of the map for example a Set needs to be used .
  class StudentInfo{
  private String name;
  private int studentID;
  StudentInfo(String n, int sid){
  name = n;
  studentID =sid;
  }
  public String toString(){
  return name + "  " + studentID;
  }
  }
  public class Hashes {
      public static void main(String args[]){
      HashMap h = new HashMap();
      h.put(new StudentInfo("Tom sanders", 56746), new Integer(19));
      h.put(new StudentInfo ("Dave Patterson", 34578), new Integer(14));
      h.put(new StudentInfo ("Julia Myers",23678), new Integer(18));
      h.put(new StudentInfo ("Scott Stephenson",56743 ), new Integer(24));
      h.put(new StudentInfo("Betty Matthews",75456), new Integer(22));
      h.put(new StudentInfo("Billy Johnson",93456), new Integer(26));
      int sum =0 , count = 0;
      Set set = h.entrySet();
      Iterator i = set.iterator();
      while (i.hasNext()){
      Map.Entry mpentry = (Map.Entry)i.next();
      Object element = mpentry.getKey();
      System.out.println(" Name and StudentId :" + element);
      System.out.println(" Age" + mpentry.getValue());
      sum += ((Integer)mpentry.getValue()).intValue();
      count = count +1;
      }
      int avg = sum/count;
      System.out.println("Average age of class is " + avg);
      }
    }


In Ruby


h.each_pair{|key,value| puts key,value, " "}
 
Ruby Code:
 
  h={["Tom Sanders"," " ,56746] => 19,["Billy Johnson"," " ,93456] =>26, ["Dave Patterson", " ",23678] => 14,["Julia Myers",
  " ",23768]=>18,["Scott Stephenson"," ",56743]=>24,["Betty Matthews"," ",75456]=>22}
  sum= 0;
  avg = 0;
  h.each{|key,values| sum = sum +values; puts "#{key}=>#{values}"; avg = sum/h.size }
  puts "Average age is " , avg


In Java


Iterator itr = hm.keySet().iterator();
'''Explanation'''


In the Java code listed above , a class is created which has the name and id class variables as members.A hashmap (as called in Java) is created with the key being the class of StudentInfo and the value being the age of the student. The point to be noted here is that the hashmaps in Java can take only objects as input parameters.This is an added burden as we need to use wrapper classes and convert even simple integers into objects (e.g. h.put(new StudentInfo("Tom sanders", 56746), new Integer(19))) .Extracting elements from a hashmap returns an element that belongs to the Object class (Object val= Hashmap(key)).


h={"Tom Sanders" => 21,"Billy Johnson" => 29, "Dave Patterson" =>
In Ruby even simple integers belong by default to the Object class.This reduces the complexity of the code as all variables are meted out the same treatment.
18,"Julia Myers" =>25,"Scott"=>29,"Betty"=>40}
puts h.values.min


Traversing through a hashmap in Java is done with the help of iterators ,while in Ruby traversing through a hash is no different than traversing an array.


package datastructures;
Ruby also offers other in built methods to do mathematical operations on arrays and hashes (((arr.inject(0){|sum,item|sum+item})) as they by default include (require in Ruby) enumerable class.
import java.util.*;
'''Conclusion'''


public class Hashmaps {
It can be observed that since Ruby is a purely Object oriented language, the syntax is very terse and concise, which increases program productivity.In the above java code, a Class StudentInfo was needed to be created to instantiate it as an object to be used as Key fields in the HashMap. In ruby on the other hand, since non-homogeneous arrays can also be used as Key or Value fields of Hashes, creating a Hash in involves only 1 line of code. To conclude Data structures in ruby like arrays and hashes are built in and are re-sizable and also  code blocks facilitates easy iteration which eases programming complexity. Hence implementing Hashes in ruby is definitely more concise and leads to writing more elegant codes.
public static void main(String args[]){
HashMap hm = new HashMap();
hm.put("Tom Sanders", new Integer(32));
hm.put("Billy Johnson", new Integer(24));
hm.put("Dave Patterson", new Integer(46));
hm.put("Julia Myers", new Integer(25));
hm.put("Scott Stephenson", new Integer(29));
hm.put("Betty Matthews", new Integer(40));
int temp;
Iterator itr = hm.keySet().iterator();
temp = ((Integer)hm.get(itr.next())).intValue();
while (itr.hasNext()){
  if (temp >((Integer)hm.get(itr.next())).intValue()){
 
  temp = ((Integer)hm.get(itr.next())).intValue();
  }
}
System.out.println(" Lowest value is "+ temp);
}


}
 
'''References'''
 
1. [http://www.amazon.com/Ruby-Nutshell-Yukihiro-Matsumoto/dp/0596002149/ref=pd_bbs_2/103-1832115-5168647?ie=UTF8&s=books&qid=1189787337&sr=8-2 Ruby in a Nutshell]
 
2.
[http://www.brainbell.com/tutorials/java/About_Ruby.htm Ruby Tutorial at Brainbell.com]
 
3. [http://www.oreillynet.com/ruby/blog/2005/12/sorting_an_array_of_hashes_wit_2.html O'Reilly Ruby]
 
4. [http://www.meshplex.org/wiki/Ruby/What_can_I_use_RoR_for Ruby documentation at MeshPlex ]
 
5. [http://rubyhacker.com/coralbook/ch3.html  Coralbook]
 
6. [http://www.softiesonrails.com/2007/8/27/ruby-101-hashes-are-cool/  Softies on Ruby]

Latest revision as of 01:57, 19 September 2007

HashMaps in Java vs Hashes in Ruby

Maps in java or hashes in ruby is any unordered object which stores associations between keys and their corresponding values, in which both keys and the values are objects. The key is unique , however the values may not necessarily be unique. The key, is used to retrieve a value from the map at a later stage after having had stored the values.

Comparing HashMaps and Hashes

1. Both in Java and Ruby, data structures are treated as objects. Hence both HashMaps and Hashes are used to store and manipulate objects which can be instantiated using the new method.

  in Java using   : HashMap h = new HashMap; 
  in Ruby using   : h = hash.new

2. In Ruby there is no difference between primitive data types and objects.Hence any variable or object can be put directly into the hashes container and methods can be invoked on them. However in Java primitive objects needs to be type casted to an Object class in order to use in built methods on the created HashMaps.

3. Ruby has the same syntactic sugar for hashes as well as arrays which makes the implementing hashes as simple as implementing an array. In Java however, since HashMaps implement the Collections framework, objects have to be inserted using the put method.

  in Java using   : h.put (New Integer(0234), "Peter Drake");
  in Ruby using   : h = {0234 => "Peter Drake"}  

4. Inbuilt iterator feature of ruby enables accessing items one at a time. However in java, Hashmaps cannot implement the Iterator interface. To implement the iteration feature , a collection view of the map for example a Set needs to be used.

  in Java using   : Iterator itr = h.keySet().iterator();
  in Ruby using   : h.each_pair{|key,value| puts key,value, " "}

Sample Codes

The following sample codes compares simplicity in implementing a HashMap in Java with Hashes in Ruby . The following codes creates a hashmap to associate names of people as keys with their ages as values. The code prints out the keys and values and also finds the average age of the group.

Java Code :

 package assgn1;
 import java.util.*;
 class StudentInfo{
 private String name;
 private int studentID;
 StudentInfo(String n, int sid){
 name = n;
 studentID =sid;
 }
 public String toString(){
 return name + "  " + studentID; 
 }
 }
 public class Hashes {
      public static void main(String args[]){
      HashMap h = new HashMap();
      h.put(new StudentInfo("Tom sanders", 56746), new Integer(19));
      h.put(new StudentInfo ("Dave Patterson", 34578), new Integer(14));
      h.put(new StudentInfo ("Julia Myers",23678), new Integer(18));
      h.put(new StudentInfo ("Scott Stephenson",56743 ), new Integer(24));
      h.put(new StudentInfo("Betty Matthews",75456), new Integer(22));
      h.put(new StudentInfo("Billy Johnson",93456), new Integer(26));
      int sum =0 , count = 0;
      Set set = h.entrySet();
      Iterator i = set.iterator();
      while (i.hasNext()){
      Map.Entry mpentry = (Map.Entry)i.next();
      Object element = mpentry.getKey();
      System.out.println(" Name and StudentId :" + element);
      System.out.println(" Age" + mpentry.getValue());
      sum += ((Integer)mpentry.getValue()).intValue();
      count = count +1;	
      }
      int avg = sum/count;
      System.out.println("Average age of class is " + avg); 
     }
    }


Ruby Code:

 h={["Tom Sanders"," " ,56746] => 19,["Billy Johnson"," " ,93456] =>26, ["Dave Patterson", " ",23678] => 14,["Julia Myers",
 " ",23768]=>18,["Scott Stephenson"," ",56743]=>24,["Betty Matthews"," ",75456]=>22}
 sum= 0;
 avg = 0;
 h.each{|key,values| sum = sum +values; puts "#{key}=>#{values}"; avg = sum/h.size }
 puts "Average age is " , avg


Explanation

In the Java code listed above , a class is created which has the name and id class variables as members.A hashmap (as called in Java) is created with the key being the class of StudentInfo and the value being the age of the student. The point to be noted here is that the hashmaps in Java can take only objects as input parameters.This is an added burden as we need to use wrapper classes and convert even simple integers into objects (e.g. h.put(new StudentInfo("Tom sanders", 56746), new Integer(19))) .Extracting elements from a hashmap returns an element that belongs to the Object class (Object val= Hashmap(key)).

In Ruby even simple integers belong by default to the Object class.This reduces the complexity of the code as all variables are meted out the same treatment.

Traversing through a hashmap in Java is done with the help of iterators ,while in Ruby traversing through a hash is no different than traversing an array.

Ruby also offers other in built methods to do mathematical operations on arrays and hashes (((arr.inject(0){|sum,item|sum+item})) as they by default include (require in Ruby) enumerable class.

Conclusion

It can be observed that since Ruby is a purely Object oriented language, the syntax is very terse and concise, which increases program productivity.In the above java code, a Class StudentInfo was needed to be created to instantiate it as an object to be used as Key fields in the HashMap. In ruby on the other hand, since non-homogeneous arrays can also be used as Key or Value fields of Hashes, creating a Hash in involves only 1 line of code. To conclude Data structures in ruby like arrays and hashes are built in and are re-sizable and also code blocks facilitates easy iteration which eases programming complexity. Hence implementing Hashes in ruby is definitely more concise and leads to writing more elegant codes.


References

1. Ruby in a Nutshell

2. Ruby Tutorial at Brainbell.com

3. O'Reilly Ruby

4. Ruby documentation at MeshPlex

5. Coralbook

6. Softies on Ruby