Results 1 to 2 of 2
  1. #1
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    286
    Rep Power
    6

    Default How do raw types of generic types show pregeneric behavior?

    Given a generic type Box like the following

    Java Code:
    class Box<T> {
      
      T methodThatTakesAndReturnsT(T t) {
        //... operate on t or something
        return t;
      }
    
    }
    we can create its raw type like

    Java Code:
    Box rawBox = new Box();
    Now from this tutorial,
    When using raw types, you essentially get pre-generics behavior a Box gives you Objects
    So from the println statement in the following code, I was expecting 'Object' to be printed.

    Java Code:
    public class RawTypeAndPreGenericBehavior {
    
    	public static void main(String[] args) {
    		
    		Box rawBox = new Box();
    		
    		System.out.println(rawBox.methodThatTakesAndReturnsT("Some string.").getClass().getSimpleName()); 
    		
    	}
    
    }
    But it printed String.

    So what do they mean by the Box giving Object. How does this raw type show pre-generics behavior?

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: How do raw types of generic types show pregeneric behavior?

    Calling getClass on a variable will give you the actual class of the object that variable references, not the class of the variable itself.
    Java Code:
    Object o = new MyClass();
    System.out.println(o.getClass.getSimpleName());
    will give MyClass, and not Object.

    For your code, the way to see the raw type in action is:
    Java Code:
    String s = rawBox.methodThatTakesAndReturnsT("Some string.");
    which will give a compiler error as methodThatTakesAndReturnsT will be returning an Object, not a String.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. Arithmetic with Generic Types
    By azalea in forum New To Java
    Replies: 3
    Last Post: 10-24-2011, 09:55 PM
  2. comparable interface, generic types
    By dylandrop in forum New To Java
    Replies: 3
    Last Post: 04-16-2011, 08:45 PM
  3. generic and different enum types
    By vojtab in forum New To Java
    Replies: 0
    Last Post: 11-08-2010, 06:11 PM
  4. Help with comparing generic types
    By repairmanjack in forum New To Java
    Replies: 4
    Last Post: 09-22-2009, 07:41 AM
  5. generic types
    By jon80 in forum New To Java
    Replies: 6
    Last Post: 06-12-2009, 11:29 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
  •