Will generics implementation eliminate runtime casting?

Before generics, one must explicitly cast when pulling out of an iterator. For example:
List l = ...
for(Iterator i = l.iterator(); i.hasNext();) {
doSomethingWithInteger((Integer)l.next());
Now with generics, we won't have to explicitly cast the return value of the iterator's .next() method:
List<Integer> l = ...
for(Iterator i = l.iterator(); i.hasNext();) {
doSomethingWithInteger(l.next());
However, form what I've seen of decompiled code compiled with the beta version of the generics compiler, there is still implicit casting going on. The return value of Iterator.next() is still being casted to an Integer. And runtime casting like this has actual instructions to be executed, not just syntactic sugar. It seems silly to me, though, since everything in the List is an Integer, there should be no need to explicitly cast it.
So will the addition of generics not be able to eliminate this overhead? Why was this decided?

It actually turns out that the runtime casts are extremely cheap to do, because modern superscalars typically have plenty of extra functional units and branch prediction on the cast is extremely accurate (all the casts inserted by JSR-14 are always true, so the branches always predict correctly).
But even though they have a negligible performance cost, they do bloat the binary. The NextGen proposal
http://doi.acm.org/10.1145/286936.286958
was always the "future" solution to this. It's the second step of the implementation. The first step is JSR-14.

Similar Messages

  • Runtime casting problems

    The following code gives me runtime casting problems:
    package edu.columbia.law.markup.test;
    import java.util.*;
    public class A {
       protected static Hashtable hash = null;
       static {
          hash = new Hashtable ();
          hash.put ("one", "value 1");
          hash.put ("two", "value 2");
       public static void main (String args []) {
           A a = new A ();
           String keys [] = a.keys ();
           for (int i = 0; i < keys.length; i++) {
               System.out.println (keys );
    public String [] keys () {
    return (String []) hash.keySet ().toArray ();
    The output on my console is:
    java.lang.ClassCastException: [Ljava.lang.Object;
            at edu.columbia.law.markup.test.A.keys(A.java:37)
            at edu.columbia.law.markup.test.A.main(A.java:29)I can not understand why is it a problem for JVM to cast?
    Any ideas?
    Thanks,
    Alex.

    return (String []) hash.keySet ().toArray ();This form of toArray returns an Object[] reference to an Object[] object. You cannot cast a reference to an Object[] object to a String[] reference for the same reason that you cannot cast a reference to a Object object to a String reference.
    You must use the alternate form of toArray instead:
    return (String []) hash.keySet ().toArray (new String[0]);This will return an Object[] reference to a String[] object, and this reference can be cast to a String[] reference.

  • Runtime Casting

    I have a hashtable with different objects types inside it. Since they are swing objects, all of them are handled by a single function.
    Enumeration enum = hash.keys();
    while( enum.hasMoreElements() )
         // The key is always a String, so a hard cast is acceptable
         String key = (String)enum.nextElement();
         Object val = hash.get(key);
         // Try Use Reflection to retrieve the class
         Class interfaceClass = Class.forName(val);    // ??
         panel.add( (interfaceClass)val  );            // ??
    }What I would like to do is cast these objects without having to write a switch statment to delimit hard casts. The following code works, but since I have to hard code the answers is *obviously a poor way to do it.
    Enumeration enum = hash.keys();
    while( enum.hasMoreElements() )
         String key = (String)enum.nextElement();
         Object val = hash.get(key);
         // Use Reflection to retrieve the class
         Class interfaceClass = val.getClass();
         String className = interfaceClass.getName();
         if( className.endsWith("JButton") )
              panel.add( (JButton)val  );
         else if( className.endsWith("JCheckBox") )
              panel.add( (JCheckBox)val  );
    }Any help with the dynamic casting problem would be appericated.
    ~Kullgen
    (PS, After searching the forums for a solution, I find that when people ask this question they are invariably flamed for poor design. This is not a design question, but just a problem with having to use the clunky java swing. IMHO Swing was very poorly designed, and thus leaves itself open to the problems above. I want this to be a post about runtime casting, not about design)

    Since all the has elements are Swing componets they are all instances
    of java.awt.Component. So simply cast to that and everything will be
    just fine and dandy. No need for lots of switch statements.
    For example:
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    public class Kullgen1
         public static void main(String[] argv)
              Hashtable hash= new Hashtable();
              hash.put("Button", new JButton("Button"));
              hash.put("Label", new JLabel("Label"));
              hash.put("TextField", new JTextField("TextField"));
              JFrame frame= new JFrame();
              JPanel panel= new JPanel(new GridLayout(0,1));
              frame.getContentPane().add(panel);
              Iterator components= hash.values().iterator();
              while(components.hasNext())
                   panel.add((Component) components.next());
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.pack();
              frame.setVisible(true);
    }

  • TS3212 Just attempted to download current update of Itunes into my HP windows 7 computer. I've never had trouble before but now it will not run. Runtime Error R6034 an app has make an attempt to load the C runtime library incorrectly. Itunes Error 7

    Just attempted to download current update of Itunes into my HP computer with Windows 7. I've never had trouble before but now it will not run. Runtime Error R6034 an app has make an attempt to load the C runtime library incorrectly. Itunes Error 7

    Click here and follow the instructions. You may need to completely remove and reinstall iTunes and all related components, or run the process multiple times; this won't normally affect its library, but that should be backed up anyway.
    (99714)

  • Error Message: Your content will not stream. Runtime Shared Library preloader will require...

    Please help. I am receiving an error message and I don't know what I need to do to fix my file. I'm working in Flash CS5.5. I've created an animated web banner. When I go to test movie, I receive the following error message:
    Your content will not stream. Runtime Shared Library (RLS) preloader will require all of your content to download before the first frame will play.
    To prevent this you can change the Runtime Shared Library Library Settings in the Advanced ActionScript 3.0 Settings dialog which can be raised from the Publish Settings dialog.
    The Runtime Shared Libraries being preloaded are:
    textLayout_2.0.0.232.swz for TLF Text
    I don't know what any of this means or what I need to do to ensure that my web banner will load correctly once it's uploaded to a website. Please help. I'm fairly new to Flash. Thank you in advance for any advice you can provide.

    Mr Benrud,
    This window means you've used TLF Text Format and before all of your content download, it requires to be proloaded. To get rid of this message, just remove TLF Text Format (if you really don't require it) or else goto Publish Settings -> Flash -> Actionscript Settings and just remove it.

  • PRODUCT COSTING ACTIVITIES AS THE PP WILL BE IMPLEMENTED IN 2ND PHASE

    Solution for CO without PP module.
    As planned, PP module will be implemented in the second phase. And we need to have solution to manage: finished good, production of Zee in first phase.
    About production of Zee.
    Zee has many subcompanies, but there are only 3 company that implemented SAP system: Zee corp, Zeetech, Zee M&E. ( Zee corp is parent company of Zeetech, Zee M&E).
    There is only Zeetech that has production.
    Products of Zeetech: air condition, chilled water fanu2026Zeetech have many workshops.
    Zeetech do many batch each of month, and there are many kind of products in each of batch.
    We used Moving price for Zee on SAP system.
    We intend to use u201Cproduction orderu201D to capture all cost related to product,
    Cost component of product:
    +raw material
    + labor cost
    + overhead cost of workshop: other costs
    + overhead cost of batch: fuel, submaterial,
    +  operation cost.
    HOW SHOULD WE TAKE CARE OF PRODUCT COSTING ACTIVITIES AS THE PP WILL BE IMPLEMENTED IN SECOND PHASE ?

    Dear Anita,
    Yes u r right that Each consultant will be prepare AS-IS & TO-BE documents for their respective modules but these BBP's are not mixed up.
    The rules of each consultant in phase 2 i e Business Blue Prints is to created bbp's or say Document which is going to configure in the SAP system along with core users.
    AS - IS means what futures client's are using in the Legacy System
    TO- BE mean what futures we are giving to client according to thier Legacy System
    Hope u will Undersatnd.
    Regards,
    Javeed

  • When will you implement recording capabilities?

    Hi!
    When will you implement recording capabilities? Both voice and video calls.
    Best regards! Jerry Kallstrom, Sweden

    The video recording stops when a call comes in & is not deleted. Tell your friend to put the phone in Airplane mode if they don't wanr to be interrupted.

  • Generics' types at runtime (JVM)

    Hi everybody
    This is gonna be a tricky question I guess.
    I'm using generics for an application of mine and I need to know the actual types of a class at runtime.
    For example, let's say I have: "Hashtable<String, Integer> ht;"
    Using Reflection I can easily find out that 'ht' is an 'Hashtable' as well as I can create an instance of Hashtable.
    But if I use 'ht.getTypeParameters()' to find out the type of the generics, I get '<K,V>' instead of
    '<String,Integer>', this because 'ht.getTypeParameters()' returns the formal types and not the actual types.
    In the same way, "Class.forName("java.util.Hashtable");" works, while
    "Class.forName("java.util.Hashtable<String,Integer>");" throws an exception because it can't find the class,
    Does anybody of you know if and how it is possible to access actual generics types at runtime?
    Thanks in advance
    michele

    Not possible. That's why we call it erasure ;-)
    There is an RFE to reify generic type arguments at runtime:
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5098163

  • Dynamically Selecting & Creating Instance of Implementation at Runtime

    I'm looking to create a instance of an implementation of a interface where the class name of the interface is both given at runtime via properties and also unknown at compile-time (the binary may be provided by another developer in a separate package). I am wondering if this is both possible, and if it is, how I can accomplish this.
    For example:
    package com.someone.else;
    public class ExternalImplementation extends Object; // This is a silly example.
    package com.me;  // In my code, in the body of some method, I would have:
    String className = "ExternalImplementation"; // This would be gotten through a Properties object and may be just the class name or whatever it takes to specify the correct class.
    Object o = /* And here, I want to create an instance of an ExternalImplementation, even though it doesn't exist at compile-time. */;Thanks for your time!
    ~ Anthop

    Ah yes, sorry - Spoon's is correct. I was mentally absent for half of my answer :) Note that it would also be enough to do:
    SomeInterface instance = (SomeInterface)Class.forInstance("ExternalImplementation").newInstance();Less typing and will give you the same error if the external imlementation doesn't in fact implement SomeInterface.

  • HT3235 Will generic DVI to VGA adapter work with Macbook Pro (Early 2008 Model)??

    I have a 15" MacBook Pro (Early 2008 model).  I lost the Apple DVI to VGA adapter for use with my projector, and it appears this older model is no longer available.  Will a generic DVI/VGA adapter, from Best Buy for example, work?  I wasn't sure if there was anything specific to the Apple adapter?  I am supposed to give a lecture in 2 days and can't find my adapter!  Any help is greatly appreciated.

    Yes it will, assuming that you do not have a display like the 30" Apple Cinema Display that requires dual-link DVI.

  • Get the Type of a generic field at runtime, How to?

    Hello,
    As the topic already says, i need to get the Type of a particular field of a class. This field is declared private and generic. In C# there is a method
    Type Object.getTypeIs there any specific way to do this in Java 1.5?
    Please excuse my poor english.
    Thanks in advance.
    Markus

    McNepp wrote:
    endasil wrote:
    McNepp wrote:
    If you want to know the parametrized type (String in the example), I think there is no way of knowing this in Java 1.5 or Java 1.6, since the parametrized type is erased and not available at run time.The type of a parameterized field is not erased.For most intents and purposes, it is. Type erasure refers to the fact that at runtime, there are not actually multiple class binaries depending on the generic arguments to a class. Therefore, an ArrayList<T> is actually just an ArrayList with no generics.
    Frankly, I don't understand why you insist that the information on generic fields that the OP was asking about is lost at runtime.I wasn't trying to insist that. At the time, I was replying more to Saish and trying to reaffirm that most information about generics is lost at run-time. I mistakenly ignored how you qualified it with "field."
    What you write about instances of generic classes losing their type information is of course correct, albeit not to the point of the original question.Nope, you're right. I was just trying to reconcile the fact that many people get confused that there's any information available at run-time, and so start down the path of thinking that type erasure doesn't exist. But it very much does.
    The original question was about how to obtain the type of a generic field.And I did show in my example that even that is fairly limited, given that if the type is provided by the parameter of the class, it doesn't give you anything useful (I'm not trying to say you said it would!).
    The compiler preservers this information in the class file, so it can be obtained at runtime. Frameworks like JPA put this to use extensively, proving that it is of real value.Definitely. However I don't see this having as much to do with generics as basic reflection functionality. If you can get the type of a field at run-time, you should be able to get the parameters as well! That should in no way belittle its value, though. But I would have guessed (knowing little about) that JPA wouldn't put that to use so much as the type parameters of an accessor return type or mutator argument type. Especially since I thought we'd shown that you would need your fields to be non-private for JPA to be able to gain information about their type.
    Edit: getDeclaredField works fine with private members, and returns the expected "java.lang.String" from jschell's example above
    Edited by: endasil on 28-Apr-2009 10:39 AM

  • Trigger a job based on a job that will be created during runtime

    I searched sdn and I did not find any threads addressing my issue(Trigger JOB B after a JOB A which will not be available untill runtime).
    My Req:
    I have a where in, a JOB 'A' will trigger to execute a BDC session in program A using a SUBMIT ...RETURN statement.
    I will have to trigger a different job 'B' using program B, the moment the 1st job runs completed.
    I thought this would be possible, by handling the events and trigger the FM in program A after the SUBMIT statement. But the problem is SUBMIT statement would just create the job and return the control back to the program A and immediately call the FM to raise the EVENT. In this case, my job B will trigger and even complete before JOB A could complete successfully.
    I tried using AFTER JOB option in SM36 instead of AFTER EVENT. The problem with this option is, JOB A will be available ONLY during runtime and hence cannot schedule program B with the option AFTER JOB.
    Any thoughts are highly appreciated.
    Thanks for your help.
    Best Regards,
    Kiran

    Hi Thomas,
    I programmed the way you mentioned and this triggers both the jobs at the same time.
    DATA: number  TYPE tbtcjob-jobcount,
          jobname LIKE tbtcjob-jobname.
    jobname  = 'JOB1'.
    CALL FUNCTION 'JOB_OPEN'
      EXPORTING
        jobname          = jobname
      IMPORTING
        jobcount         = number
      EXCEPTIONS
        cant_create_job  = 1
        invalid_job_data = 2
        jobname_missing  = 3
        OTHERS           = 4.
    IF sy-subrc <> 0.
      MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
              WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
    ELSE.
      SUBMIT zhbn_life_premium_summary_rpt
      VIA JOB    jobname
          NUMBER number
          AND    RETURN.
      IF sy-subrc EQ 0.
        CLEAR: jobname.
        jobname = 'JOB2'.
        CALL FUNCTION 'JOB_OPEN'
          EXPORTING
            jobname          = jobname
          IMPORTING
            jobcount         = number
          EXCEPTIONS
            cant_create_job  = 1
            invalid_job_data = 2
            jobname_missing  = 3
            OTHERS           = 4.
        IF sy-subrc <> 0.
          MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
                  WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
        ELSE.
          SUBMIT zhbn_life_premium_summary_rpt
          VIA JOB    jobname
              NUMBER number
              AND    RETURN.
          IF sy-subrc EQ 0.
            WRITE: 'job 2 success'.
            jobname = 'JOB2'.
            CALL FUNCTION 'JOB_CLOSE'
              EXPORTING
                jobcount             = number
                jobname              = jobname
                strtimmed            = 'X'
              EXCEPTIONS
                cant_start_immediate = 1
                invalid_startdate    = 2
                jobname_missing      = 3
                job_close_failed     = 4
                job_nosteps          = 5
                job_notex            = 6
                lock_failed          = 7
                invalid_target       = 8
                OTHERS               = 9.
            IF sy-subrc <> 0.
              MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
                      WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
            ENDIF.
          ENDIF.
        ENDIF.
      ENDIF.
      jobname = 'JOB1'.
      CALL FUNCTION 'JOB_CLOSE'
        EXPORTING
          jobcount             = number
          jobname              = jobname
          strtimmed            = 'X'
        EXCEPTIONS
          cant_start_immediate = 1
          invalid_startdate    = 2
          jobname_missing      = 3
          job_close_failed     = 4
          job_nosteps          = 5
          job_notex            = 6
          lock_failed          = 7
          invalid_target       = 8
          OTHERS               = 9.
      IF sy-subrc <> 0.
        MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
                WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
      ENDIF.
    ENDIF.
    Am I missing anything?
    Thanks
    Kiran

  • When will Reader 9's Runtime error for redirected Application Data be fixed??

    Has anyone heard when Adobe will fix Reader 9's Runtime error for redirected Application Data??  It's still happening with 9.1.3 for only users who have their Application Data folder redirected via Group Policy.
    It's been going on for some time, as evidenced by the following link, and my own personal pain fighting this
    http://forums.adobe.com/thread/391738?start=100&tstart=0

    Also posted here: http://forums.adobe.com/thread/391738
    I haven't read through all of the posts, but the general consensus I have is that the issue is in fact related to the redir
    ection of the Application Data folder. The main issue being that the use of a UNC path causes the error described, with some mention to explicit user permissions on the root of the folder path.
    I was just recently made aware of this issue in our environment. Apparently we've held off upgrading to Adobe 9.x because of this issue. After a little research, it was apparent that simply modifying the default Folder Redirection policies is not possible because the use of a mapped drive is not supported.
    I haven't had a chance to test this yet, and may not be able to for some time, so I thought I would share this in case someone else might be able to test. The idea being to simply use a custom ADM file to force the redirection of certain profile folders. Again, I haven't tested this using a mapped drive in the path, but I have successfully used the same settings below to redirect other folders not available by default in Group Policy.
    1) Copy the text between ----- Start of ADM ------ and ----- End of ADM ------ and paste it into a text file.
    2) Rename the .txt to .adm.
    3) Load the ADM template into a GPO.
    4) Right click "USER Custom Settings", select "View", select "Filtering" and uncheck the option "Only show policy settings that can be fully managed".
    5) Configure the "Redirect Application Data" option as enabled, and enter a mapped drive path.
    6) Test.
    I'm interested to hear if this is a viable solution or not.
    ------ Start of ADM -----
    CLASS USER
          CATEGORY "USER Custom Settings"
                CATEGORY "Folder Redirection Settings"
                      POLICY "Redirect My Documents"
                      EXPLAIN "By default files are stored as part of the
    user's profile.\n\nConfigure alternative locations here."
                      KEYNAME
    "Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders"
                      PART "Redirect to" EDITTEXT
                            VALUENAME "Personal"
                            MAXLEN 255
                            DEFAULT ""
                            EXPANDABLETEXT
                      END PART
                      END POLICY ; RedirectHistory
                      POLICY "Redirect Application Data"
                      KEYNAME
    "Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders"
                      EXPLAIN "By default files are stored as part of the
    user's profile.\n\nConfigure alternative locations here."
                      PART "Redirect to" EDITTEXT
                            VALUENAME "AppData"
                            MAXLEN 255
                            DEFAULT ""
                            EXPANDABLETEXT
                      END PART
                      END POLICY ; RedirectHistory
                      POLICY "Redirect Cookies"
                      KEYNAME
    "Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders"
                      EXPLAIN "By default files are stored as part of the
    user's profile.\n\nConfigure alternative locations here."
                      PART "Redirect to" EDITTEXT
                            VALUENAME "Cookies"
                            MAXLEN 255
                            DEFAULT ""
                            EXPANDABLETEXT
                      END PART
                      END POLICY ; RedirectCookies
                      POLICY "Redirect Favorites"
                      KEYNAME
    "Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders"
                      EXPLAIN "By default files are stored as part of the
    user's profile.\n\nConfigure alternative locations here."
                      PART "Redirect to" EDITTEXT
                            VALUENAME "Favorites"
                            MAXLEN 255
                            DEFAULT ""
                            EXPANDABLETEXT
                      END PART
                      END POLICY ; RedirectFavorites
                      POLICY "Redirect History"
                      KEYNAME
    "Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders"
                      EXPLAIN "By default files are stored as part of the
    user's profile.\n\nConfigure alternative locations here."
                      PART "Redirect to" EDITTEXT
                            VALUENAME "History"
                            MAXLEN 255
                            DEFAULT ""
                            EXPANDABLETEXT
                      END PART
                      END POLICY ; RedirectHistory
                      POLICY "Redirect Recent Documents"
                      KEYNAME
    "Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders"
                      EXPLAIN "By default files are stored as part of the
    user's profile.\n\nConfigure alternative locations here."
                      PART "Redirect to" EDITTEXT
                            VALUENAME "Recent"
                            MAXLEN 255
                            DEFAULT ""
                            EXPANDABLETEXT
                      END PART
                      END POLICY ; RedirectRecent
                END CATEGORY
          END CATEGORY
    ------ END of ADM -----

  • When will ngmoco's eliminate pro be back in the appstore?

    I have noticed that Ngmoco's Eliminate Pro has been taken down from the Appstore, and was wondering if it will be put back up, and if so, when?
    (sorry if i posted this in the wrong area on the website, Im new to this)

    Hi Gabe ...
    This being a user to user forum, not Apple, we have no way of knowing if and when apps will be available in the future.
    You posted in the right community
    Welcome to Apple Support Communities.
    When you get a chance, check out the Apple Support Communities - Tutorials.
    edited by:  cs

  • Getting generic type at runtime

    Example:
    public class GenericTest {
    private List<String> list = new List<String>();
    How can I get the type String at runtime?
    Class c = GenericTest.class;
    Field[] fiels = c.getFields();
    for (Field f: fields) {
    Class fc = f.getDeclaringClass();
    // What are the next steps to to get String.class from fc?
    }

    Generic types (ie. the ones inside the < >) get Erased at compile-time. All this type information is therefore not available at run-time
    Google "Java Generics Erasure" to get some more info. (There's a Generics forum by the way!)

Maybe you are looking for