Or Email

Generics: JAVA vs. NET

By Gal Ratner

Both SUN and Microsoft have added Generics to JAVA 1.5 and .NET 2.0 and since Generics can significantly improve the performance of your program, it will be a good idea to incorporate it into almost any algorithm that uses lists in order to hold data.
In this article I will explain what Generics is and how to implement it using JAVA and .NET

What is Generics?
Generics is the ability to tell the compiler in design time what is the type of the collection we are about to work with.
In forth generation languages, every type can be cased to "Object", which is the universal base class for any custom or built-in object.
When building a collection from your custom object, the compiler casts your type (for example: string or an integer) into "Object" and adds it to the collection.
During runtime, when, your code needs to access elements in the collection, you must cast the desired element back into the original type. If the compiler cannot cast this element back, a runtime error is thrown.
In a generic collection, you must specify the native type; your collection is going to hold. The compiler then generates a collection that can only hold your custom type without any option to store a type that does not belong in this collection.

Why is Generics faster?
It's simple. There are no extra "gaps" in memory. The compiler does not create extra room for the universal "Object" type and doesn't spend any time casting objects into your desired type. There are a few types of generic collections in the JAVA and .NET Framework .In this example we will work with the simplest one: a generic List.

Here is how to work with generic lists:
First let's import the classes we need

import java.util.*;

using System.Collections.Generic;

Second: let's define a generic list that will hold only "string".

List<String> list = new ArrayList<String>();

List<string> list = new List<string>();

In order to add elements:

String elementString = "Element to find";

string elementString = "Element to find";

Now lets find the element we have just added:

for (Iterator ilist = list.iterator(); ilist.hasNext(); )
   if (ilist.next().equals("Element to find")) // Do somthing

foreach(string s in list)
   if(s.Equals("Element to find")) // Do somthing

This is it. Simple modifications in your existing program will allow you to speed up your code and put Generics into work for you!

About Us | Contact Us | Standards of Business Conduct | Employment
InvertedSoftware.com All rights reserved