Thursday, November 7, 2013

Generics

Generics is a powerful feature in Java programming language. It is implemented in Collections Framework of Java. The Generics allows you to create generic class, interface, method, and variable. A generic class, interface, method, or variable can work with different types of data because you can specify the type of data as a parameter. Since the generic class, interface, method, or variable does not restrict the type of data when it is defined, it can be reused. For example, you can create only a LinkedList class to store text, integer values, or floating-point values.
You can create a generic class or interface by placing the generic type parameter between the smaller and the greater signs (< and >) after name of the class. The example code below creates a generic class called ListNode. T is the generic type parameter. When you define a generic method or variable, you can place the generic type parameter as you do with a normal data type. This generic type parameter must be the same as the generic type parameter defined with the class.

Example:

class ListNode<T>
{
  public T val;
  public ListNode<T> next;
  public ListNode(T val) { this.val = val; next = null; }

}

When you use a generic class to store value by creating an object and pass the value to it, you should specify the specific data type of the value.

Example:

ListNote<Integer> node=new ListNode<Integer>(123);

You can use many generic type parameters in a class, interface, or methods. You will need to separate the type parameters by comma. See the example below.
Example:

class MyMap<T1,T2>{
  private T1 key;
  private T2 value;
  MyMap(T1 key, T2 value){
    this.key=key;
    this.value=value;
  }
}


Here is the complete LinkedList program that uses the Generics feature.

class ListNode<T>
    {
        public T val;
        public ListNode<T> next;
        public ListNode(T val) { this.val =val; next = null; }
       

    }

interface ListOperations<T>
    {
        void insertNode(T val, int post);
        void deleteNode(int post);
        void printList();
       
    }
class LinkedList<T> implements ListOperations<T>

{
    protected ListNode<T> pfirst; //pfirst points to the first element of the linked list
    protected ListNode<T> plast;//plast points to the last element of the linked list
    protected int NumItems;
    public LinkedList() { pfirst = plast = null; NumItems = 0; }
    
    public void insertNode(T val,int post)
    {
        ListNode<T> newNode = new ListNode<T>(val);
        if (pfirst == null)
        {
            pfirst = newNode;
            plast = newNode;
            NumItems++;

        }
        else
        {
            if (post == 1)
            {
                newNode.next = pfirst;
                pfirst =newNode;
                NumItems++;
            }

            else if(post>1 && post<=NumItems){
                ListNode<T> ta = pfirst;
                for (int i = 1; i < post - 1; i++) ta = ta.next;
                newNode.next = ta.next;
                ta.next = newNode;
                NumItems++;
            }
            else if (post == (NumItems + 1))
            {
                plast.next = newNode;
                plast = newNode;
                NumItems++;
            }
            else
            {
                System.out.println("Invalid position");

            }


        }

    }
    public void deleteNode(int post)
    {
        if (pfirst == null)
        {
        System.out.println("Empty list");
            return;
        }

        if (post == 1)
        {
            if (NumItems == 1)
            {
                pfirst = null;
                plast = null;
            }
            else
            {
                ListNode<T> temp = pfirst;
                pfirst = pfirst.next;
                temp = null;
            }
        }
        else if(post>=1 && post<=NumItems){
            ListNode<T> temp, ta;
            ta = pfirst;
            for(int i=0;i<post-1;i++) ta=ta.next;
            temp = ta.next;
            ta.next = temp.next;
            if (temp.next == null) plast = ta;
            temp = null;
        }

    }
    public void printList()
    {
        ListNode<T> ta = pfirst;
        while (ta != null)
        {
        System.out.println(ta.val);
            ta = ta.next;
        }
    }
    
    

public Object[] toArray(){

  Object[] arr=new Object[NumItems];
  ListNode<T> ta = pfirst;
  int i=0;
       while (ta != null)
       {
          arr[i]=ta.val;
           ta = ta.next;
           i++;
       }
       
       return arr;
  
   }
   

}



public class GenericsJava {
public static void main(String[] args){
//Creating linked list to store text
LinkedList<String> lstString = new LinkedList<String>();
lstString.insertNode("Item1", 1);
lstString.insertNode("Item2", 2);
lstString.insertNode("Item3", 3);
lstString.printList();
//creating linked list to store numbers
LinkedList<Integer> lstNumber = new LinkedList<Integer>();
lstNumber.insertNode(10, 1);
lstNumber.insertNode(13, 2);
lstNumber.insertNode(13, 3);
lstNumber.printList();

}


}

12 comments:

  1. Inventiveness is the great method to make the ad and it is useful for the general population. This sort of the imagination is extremely viable and it is a decent wellspring of the data and you can join essay-company review service for wonderful task. The material that you post in this article is extremely useful.

    ReplyDelete
  2. The information you share is very useful. It is closely related to my work and has helped me grow.

    ReplyDelete
  3. Hey! Do you know if they make any plugins to help with Search Engine Optimization? I'm trying to get my post to rank for some targeted keywords but I'm not seeing very good gains. If you know of any please share. Many thanks! I know this if off topic but I'm looking into starting my own wepost and was curious what all is needed to get set up? I'm assuming having a post like yours would cost a pretty penny? I'm not very internet savvy so I'm not 100% sure. Any tips or advice would be greatly appreciated. Thank you developers in singapore

    ReplyDelete
  4. whoah this weblog is magnificent i like studying your articles. Stay up the great work! You already know, a lot of people are searching round for this information, you could help them greatly. maternity gowns

    ReplyDelete
  5. Admiring the time and effort you put into your blog and in depth information you offer. It's nice to come across a blog every once in a while that isn't the same old rehashed material. Excellent read! I've saved your site and I'm including your RSS feeds to my Google account.one piece ski suit womens

    ReplyDelete
  6. I have fun with, cause I found exactly what I used to be looking for. You have ended my four day long hunt! God Bless you man. Have a great day. Bye seo search engine marketing

    ReplyDelete
  7. hello there and thank you on your information – I have certainly picked up something new from right here. I did on the other hand expertise some technical issues the usage of this web site, as I skilled to reload the site a lot of times previous to I may just get it to load correctly. I have been thinking about in case your web host is OK? Now not that I am complaining, but sluggish loading instances times will often have an effect on your placement in google and could damage your quality ranking if advertising and ***********|advertising|advertising|advertising and *********** with Adwords. Well I’m adding this RSS to my e-mail and can glance out for a lot more of your respective intriguing content. Make sure you update this again soon.. online advertisement

    ReplyDelete
  8. Thanks on your marvelous posting! I seriously enjoyed reading it, you happen to be a great author.I will be sure to bookmark your post and definitely will come back someday. I want to encourage you to ultimately continue your great work, have a nice weekend! cheapest private jet

    ReplyDelete
  9. Hello.This post was really remarkable, particularly because I was browsing for thoughts on this subject last week. You made some decent points there. I looked on the internet for the subject and found most persons will approve with your post. I am continually invstigating online for ideas that can aid me. Thanks! wayanad homestay

    ReplyDelete
  10. Aw, this was a really nice post. In thought I would like to put in writing like this moreover – taking time and precise effort to make an excellent article… but what can I say… I procrastinate alot and in no way seem to get one thing done.
    website designer

    ReplyDelete
  11. Greetings! I know this is somewhat off topic but I was wondering which blog platform are you using for this site? I'm getting sick and tired of Wordpress because I've had problems with hackers and I'm looking at options for another platform. I would be great if you could point me in the direction of a good platform.
    popular with retailers

    ReplyDelete