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

}


}

21 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. 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
  9. 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
  10. Good day! This post couldn't be written any better! Reading this post reminds me of my old room mate! He always kept chatting about this. I will forward this page to him. Fairly certain he will have a good read. Many thanks for sharing! will writing singapore

    ReplyDelete
  11. Hey there! I could have sworn I've been to this website before but after reading through some of the post I realized it's new to me. Nonetheless, I'm definitely delighted I found it and I'll be book-marking and checking back frequently! blackmores fish oil


    ReplyDelete
  12. Hey! I know this is kind of off topic but I was wondering if you knew where I could locate a captcha plugin for my comment form? I'm using the same blog platform as yours and I'm having trouble finding one? Thanks a lot! virtual agm singapore

    ReplyDelete
  13. Hey! Someone in my Facebook group shared this website with us so I came to check it out. I'm definitely enjoying the information. I'm bookmarking and will be tweeting this to my followers! Wonderful blog and excellent design and style. custom necklace

    ReplyDelete
  14. My mate and I totally love your blog and find in every way that really matters, the total of your post's to be the thing positively I'm searching for. Would you offer visitor scholars to frame content for yourself? I wouldn't see any issues with influencing a post or explaining a huge bundle of the subjects you to make stressed here. Once more, incredible site!

    best carpenter Singapore

    ReplyDelete
  15. At this time it sounds like Movable Type is the best blogging platform out there right now. (from what I've read) Is that what you're using on your blog? Evoucher

    ReplyDelete
  16. I'm truly enjoying the design and layout of your website. It's a very easy on the eyes which makes it much more enjoyable for me to come here and visit more often. buy solidworks

    ReplyDelete
  17. My brother suggested I might like this blog. He was totally right. This post actually made my day. You can not imagine simply how much time I had spent for this info! Thanks! safety vest Singapore

    ReplyDelete
  18. Thank you for sharing the above information. You are right Generics is a powerful feature in Java programming language. There are numerous reasons why your PC might not be fully optimized for gaming, such as outdated drivers or malware. A low frame rate does not make for an enjoyable gaming experience, so it is critical to understand why it is not as high as it should be. Go through this article to know the importance of FPS in games.

    ReplyDelete
  19. I read your full article and I like very much. One Of The Best Blog Which I Found. The Xbox Wireless Controller is generally regarded as the greatest PC controller. This Xbox Series X/S period controller has wired, Bluetooth, or 2.4GHz wireless connectivity, is offered in a variety of colours, is reasonably priced, and works well right out of the box with the widest selection of PC games. Read about Xbox One Controller.

    ReplyDelete
  20. Bravo to the author for their ability to capture the essence of the subject in such a concise format. This article is a testament to their expertise. Research has shown that approximately 8% of men worldwide have some form of color vision deficiency, whereas only about 0.5% of women experience the condition. The higher prevalence in men can be attributed to the inheritance patterns of X-linked genetic traits. Visit this article to know more about men are more colorblind than woman.

    ReplyDelete
  21. Bravo to the writer for delivering such a well-crafted piece. The simplicity of the language used made it accessible to all readers. I've been experiencing a strange problem with my mobile phone vibrator. It's not vibrating consistently and sometimes feels weak. Has anyone else encountered this issue? Visit this article to know more about Mobile phone vibrator ploblem.

    ReplyDelete