Results 1 to 3 of 3

Thread: Generics

  1. #1
    sireesha is offline Member
    Join Date
    Nov 2007
    Posts
    50
    Rep Power
    0

    Question Generics

    Hi,
    I am placing some code here...
    Java Code:
    public class GenericBox1
    {
       public <U> void inspect(U u)
       {
           System.out.println(u.getClass().getName());
       }        
       public static void main(String[] args)
       {
         GenericBox1 ob=new GenericBox1();
         System.out.println("Passing Integer object");
         ob.inspect(new Integer(10));
         System.out.println("Passing Double object");
         ob.inspect(10.34); //..............see this line                            
         System.out.println("Passing String object");
         ob.inspect("affaffaf");
         Integer intobject=new Integer(24);
         System.out.println("Passing Integer object");
         ob.inspect(intobject);
       }
        }
    In my code i am passing a primitive type 10.34 instead of a object.
    But i read that we can't pass primitive types as a formal type parameter in generics use.
    But here i did it.
    but it didn't show any error.it works well.
    what is the reason for this ?
    is this the example for auto boxing and unboxing ?

  2. #2
    roots's Avatar
    roots is offline Moderator
    Join Date
    Jan 2008
    Location
    Dallas
    Posts
    293
    Rep Power
    10

    Default

    Yes this is an example of Autoboxing and unboxing ..
    can't pass primitive types as a formal type parameter in generics use
    Java Code:
    public class Box<E> {
    	private E e;
    
    	public E getE() {
    		return e;
    	}
    
    	public void setE(E e) {
    		this.e = e;
    	}
    
    	public static void main(String[] args) throws Exception {
    		Box<Integer> ok = new Box<Integer>();		
    		Box<int> no-ok = new Box<int>(); // This doesnot work
    	}
    }
    dont worry newbie, we got you covered.

  3. #3
    sireesha is offline Member
    Join Date
    Nov 2007
    Posts
    50
    Rep Power
    0

Similar Threads

  1. Help w/ generics
    By Hollywood in forum New To Java
    Replies: 2
    Last Post: 02-16-2008, 04:08 AM
  2. Generics
    By eva in forum New To Java
    Replies: 2
    Last Post: 01-04-2008, 10:10 PM
  3. Java confused over Generics?
    By Bibendum in forum New To Java
    Replies: 3
    Last Post: 12-26-2007, 07:23 AM
  4. Java Generics (an introduction)
    By Java Tutorial in forum Java Tutorial
    Replies: 0
    Last Post: 11-27-2007, 07:50 PM
  5. ArrayList<type> - Generics
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 11-14-2007, 04:21 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •