Use of generics in the Map interface

After using Java 1.5 for a while, I've gotten pretty comfortable using generics and the collections framework. Very often, I depend on the new generics-related compiler warnings to guide me when I've made changes to my code. Recently, I missed a fairly subtle bug because of the following issue. Why isn't the get() method in the java.util.Map interface declared as:
V get(K key);Is there some subtle reason why this method isn't declared to enforce the generic type K for the key value? Likewise for containsKey() and remove() as well.
Thanks!

So where is the problem to use K in the first
place??The cast to K is removed during complilation. It's
not going to do anything at runtime.
Just because a reference is of type Object doesn't
mean it's not a K.
If I get an Object of unknown type, why should I have
to down-cast it just so that I can check to see
whether it is in the Map?
To state the point I wrote this simple code:
        Map<String,Integer> testMap = new TreeMap<String,Integer>();
        testMap.put("test", Integer.valueOf(100));
        // test the get method
        Integer value = testMap.get("test");
        System.out.println("First value: " + value);
        // test the method with differing parameter
        value = testMap.get(Float.valueOf(2));
        System.out.println("Second value: " + value);The code compiles without any error (so far so good) but the execution of this code results in Exception in thread "main" java.lang.ClassCastException: java.lang.String
     at java.lang.Float.compareTo(Unknown Source)
     at java.util.TreeMap.compare(Unknown Source)
     at java.util.TreeMap.getEntry(Unknown Source)
     at java.util.TreeMap.get(Unknown Source)
     at MapTest.main(MapTest.java:27)So when the Object parameter is allowed (I'm okay with that) why the ClassCastException. A similar approach to the implementations of Lists would be necessary. The current implementation is not satisfactory.

Similar Messages

  • How to set a digital output using a switch on the operator interface?

    Hi, is it possible to set a digital output using a switch on the operator interface?
    Thanks,
    Mike

    Unfortunately, no.  It is on our hit list...
    This account is no longer active. Contact ShadesOfGray for current posts and information.

  • Why the HashMap implements the Map interface twice

    See the type hierarchy below:
    HashMap<K,V>
    &#9475;
    &#9507;AbstractMap<K,V>
    &#9475;&#9475;
    &#9475;&#9495;Map<K,V>
    &#9495;Map<K,V>
    The HashMap extends AbstractMap, which implements Map. So the HashMap has already implements Map, and has the Map type. But the HashMap's declaration still contains "implements Map".
    So why the HashMap implements the Map interface twice?
    Thanks in advance.

    georgemc wrote:
    Maybe the guy who wrote HashMap wanted to make it clear that HashMap implemented Map, rather than rely on you looking further up the hierarchy to find outYes, it does make the Javadoc clearer. If they hadn't done that then there would have been legions of newbies who couldn't tell that HashMap implemented Map and thousands of "I have a doubt, does HashMap implement Map" questions here.

  • Generics hierarchy in extending interfaces

    Let's say I have an interface like this:
    package source;
    import java.util.List;
    public interface ITest <GTest extends List> {
        public void setList(GTest list);
    }I extend that interface to have a new one whose generic is an implementation of the generic of the original interface:
    package source;
    import java.util.ArrayList;
    public interface ITestEx extends ITest<ArrayList> {
    }Then I write a class which inspects the extended interface to enumerate its methods with their parameters:
    package source;
    import java.lang.reflect.Method;
    public class Test {
        public static void main(String[] args) {
            Method methods[] = ITestEx.class.getMethods();
            for (int nMethod = 0; nMethod < methods.length; nMethod++) {
                System.out.println("\nMethod #" + nMethod + ": " + methods[nMethod].getName());
                Class<?>[] parameterTypes = methods[nMethod].getParameterTypes();
                for (int nParameterType = 0; nParameterType < parameterTypes.length; nParameterType++) {
                    System.out.println("Parameter type #" + nParameterType + ": " + parameterTypes[nParameterType].getName());
    }The output is:
    Method #0: setList
    Parameter type #0: java.util.List
    That is, the argument of the setList(GTest) method is retrieved as List, which is the type GTest was declared to be in the base interface (ITest), even though getMethods() was called on its subinterface (ITestEx), which declares the generic as ArrayList.
    Is it possible to use reflection in a way that in this case would retrieve the argument of setList(GTest) as ArrayList ?
    P.S. We have been pointed to http://www.ibm.com/developerworks/library/j-cwt11085.html , but we couldn't understand whether it might help.
    Edited by: SantiBailors on Sep 19, 2007 3:25 PM

    Hi, I've altered your code by adding a helper method getTypes that maps formal type arguments to actual types. Now it prints the "real" type names. HTH
    public static void main(String[] args) {
              Map<TypeVariable<?>, Type> types = getTypes(ITestEx.class, ITest.class);
              Method methods[] = ITestEx.class.getMethods();
              for (int nMethod = 0; nMethod < methods.length; nMethod++) {
                   System.out.println("\nMethod #" + nMethod + ": " + methods[nMethod].getName());
                   Type[] parameterTypes = methods[nMethod].getGenericParameterTypes();
                   for (int nParameterType = 0; nParameterType < parameterTypes.length; nParameterType++) {
                        if (types.containsKey(parameterTypes[nParameterType]))
                             System.out.println("Parameter type #" + nParameterType + ": "
                                       + types.get(parameterTypes[nParameterType]));
                        else
                             System.out.println("Parameter type #" + nParameterType + ": " + parameterTypes[nParameterType]);
         private static <T> Map<TypeVariable<?>, Type> getTypes(Class<? extends T> cl, Class<T> genericInterface) {
              Map<TypeVariable<?>, Type> typeMapping = new HashMap<TypeVariable<?>, Type>();
              for (Type t : cl.getGenericInterfaces()) {
                   if (t instanceof ParameterizedType) {
                        ParameterizedType pt = (ParameterizedType)t;
                        if (pt.getRawType().equals(genericInterface)) {
                             for (int i = 0; i < genericInterface.getTypeParameters().length; ++i)
                                  typeMapping.put(genericInterface.getTypeParameters(), pt.getActualTypeArguments()[i]);
                             break;
              return typeMapping;
    Edited by: McNepp on Sep 20, 2007 12:14 PM

  • Forms 5.0 OLE2 and MAPI interface

    Does anyone know where I can get documentation on the MAPI
    interface commands that are used with the OLE2 forms built in
    package?
    null

    You can't. Upgrade to Forms 6 or 9.

  • I am using iPhoto 9.  My map in places quit showing. How can I get it back?

    I am using iPhoto 09.  the map feature on places quit showing up in my application.  Does anyone have an idea how to get the map feature back?

    just got off the phone with Apple - last night 30 mins & today 2 hrs.  I had the problem on my i-mac and then check my wife's macbook both with OS LION.  It appears that the files in the Cookies folder needed to be deleted to fix the problem.  No other files needed to be deleted in any other folders.  Other postings have indicated they needed to be.  But I only deleted the 4 files in the Cookies folder on my wifes Macbook & that took care of the problem.

  • Using of SALERT_CREATE in PI mapping (RFC LOOKUPs)

    I have a stupid question on using SALERT_CREATE rfc in SAP PI mapping, I am using RFC lookups in the mapping, how can I use this SALERT_CREATE RFC, Do I need to Import from PI server? do I need Communication Channel for this? How can I use to send Alerts to PI alert inbox from PI Mapping using SALERT_CREATE

    Thanks for reply Praveen, this is file to PI to File scenario, I am calling 3 RFC Lookups from Mapping, after every RFC Lookup call there are some validation checks to send alerts with out breaking the Mapping/business flow, so how can I use SALERT_CREATE rfc from mapping to send alerts

  • What things use up data on the iPhone 4? Also, what things take up space? Is it just like the iPod touch as far as space goes?

    I'm getting an iPhone and I want to know what I am looking for in data usage and space? Let me know?
    Thanks

    Anything that uses a network connection will use data, unless a wifi network is available to use (wifi does not count against your cellular 3G data use).  So email, web surfing, streaming video, updating content in news reader apps - anything like that.  Location based services as well, although there are GPS navigation apps that store their maps on the device, so do not need a data connection like the built in maps app (which uses data to fetch the map display data).  TomTom, Garmin and others have apps that include the maps stored on the device, and some, like MotionGPS allow you to cache maps for use later without a data connection.
    Pics, video's and music can also all be managed by only syncing what you want for the time being.  As long as you don't mind manipulating the sync settings and sync'ing more frequently, then you can still have a big music or photo library, just not all on the iPhone at one time.  Same goes for eBooks - as long as you don't want to keep a huge library on the device, just sync, read and remove when finished and put the next one on there (and eBooks take up very little space anyway - very compact format for ePub books).
    It sounds like 16Gb would be alright for you, but just remember you cannot upgrade the memory later.
    Also be aware of data settings.  If you use push email, it will use wifi if available when the phone is awake/active, but in sleep mode it will continue to work, but will use cellular data (since wifi is disabled when the phone enters sleep mode).  Manual fetch for email is a better way to control email data use.
    If you get unlimited social networking data use, that sounds nice (not an option with any plan I know of in the USA) - just be sure they explain it clearly (i.e. is it tied to a particular app. or only via web connections to sites - in other words how do you use it to ensure it falls into the unlimited bucket and not crosses over into your limited general data bucket).
    Enjoy!

  • Access an interface node : the mapping has not been completed

    Hello all,
    by getting an element of interface-node within a component I get follow error message
    "the mapping to node COMPONENTCONTROLLER.1.INIT_DATA" has not been completed"
    Can anybody say me, what does it mean?
    Some more information (in case for somebody need it):
    1. I have  a component A, where I have defined usage component of component B.
    2. Component B has an interface node INIT_DATA, which is mapped with the node INIT_DATA of component A.
    3. I set attributes of node INIT_DATA of component A and expect, that those values will be assigned to the node INIT_DATA of component B (becouse they are mapped)
    4. by doing it within a component A:
    lo_node = wd_context->get_child_node( name = if_componentcontroller->wdctx=>init_data).
    lo_elem->get_element( ).
    lo_elem->set_attribute(....).
    I get this error message:
    "the mapping to node COMPONENTCONTROLLER.1.INIT_DATA" has not been completed"
    Please let me know, what I do wrong?
    thanks in advance
    Anna

    Hi Anna,
    You should not be having the node INIT_DATA defined separately in both components. It should be defined only in component B and marked as Interface node. Now when you define a usage of component B in component A, you will be able to see this node. You need to map this in component A by drag and drop.
    Also, in the properties tab of the component controller of component A, declare the usage of component B using the F4 help. I think that should solve your problem.
    Regards
    Nithya

  • To retrieve the mapping expression of a particular column of an Interface

    How to retrieve the mapping expression corresponding to a particular column(say BATCH_ID) in the target table of the interface in IKM...?
    Using getColList() method all the mappings in the interface are retrieved.
    Is there a way to get the mapping for a single column using an API in IKM...?
    Thanks,
    Soumya

    Hi Soumya,
    You can define a User Defined Flag on your target and use it to get your column.
    For example, select the UD1 checkbox for BATCH_ID.
    If your KM task, pass an additional parameter (pSelector) to getColList : "UD1"
    http://docs.oracle.com/cd/E14571_01/integrate.1111/e12645/odiref_reference.htm#CIADFCFJ
    Hope it helps.
    Regards,
    JeromeFr
    [Edit] DecaXD was faster ;)

  • What is the use of Generic class in java

    hi everyone,
    i want to know that
    what is the use of Generic class in java ?
    regards,
    dhruvang

    Simplistically...
    A method is a block of code that makes some Objects in the block of code abstract (those abstract Objects are the parameters of the method). This allows us to reuse the method passing in different Objects (arguments) each time.
    In a similar way, Generics allows us to take a Class and make some of the types in the class abstract. (These types are the type parameters of the class). This allows us to reuse the class, passing in different types each time we use it.
    We write type parameters (when we declare) and type arguments (when we use) inside < >.
    For example the List class has a Type Parameter which makes the type of the things in the list become abstract.
    A List<String> is a list of Strings, it has a method "void add(String)" and a method "String get(int)".
    A List<File> is a list of Files, it has a method "void add(File)" and a method "File get(int)".
    List is just one class (interface actually but don't worry about that), but we can specify different type arguments which means the methods use this abstract type rather than a fixed concrete type in their declarations.
    Why?
    You spend a little more effort describing your types (List<String> instead of just List), and as a benefit, you, and anyone else who reads your code, and the compiler (which also reads your code) know more accurately the types of things. Because more detail is known, the compiler is able to tell you when you screw up (as opposed to finding out at runtime). And people understand your code better.
    Once you get used to them, its a bit like the difference between black and white TV, and colour TV. When you see code that doesn't specify the type parameters, you just get the feeling that you are missing out on something. When I see an API with List as a return type or argument type, I think "List of what?". When I see List<String>, I know much more about that parameter or return type.
    Bruce

  • How can i use the maps in language which different...

    i do use the phone in English interface. but to navigate in the Middle East is very hard because the spelling of the names of the street is so different. So better to navigate in Arabic. when i switched the phone to Arabic the maps switch too. but i wish if there is anyway to keep the phone in English and the map in Arabic ..... any ideas ??!!!

    If you are referring to the displayed names, then no - this is determined by the phone language settings, but if you are referring to voice guidance then it's as easy as pie - the Maps voice guidance language is not linked to the UI language, you can download voice files to the phone using either Map Loader or Ovi Suite, then you just need to go in Maps to Options>Tools>Settings>Navigation>Voice guidance and select Arabic.
    It is also possible to download the voice files directly to the phone, though the download is likely to be several megabites so beware if you are using a chargeable connection. Simply make sure that Maps is online (Options>Tools>Go online) then select the Arabic language as I guided above and it will ask you to confirm that you want to download the voice files and then do it.
    The very latest Maps version, 3.03, also includes a new feature to read out the street names, so instead of just "In 100 metres turn right", it would say "In 100 metres, turn right into High Street"; but unfortunatelty this new feature is only so far available in a small number of languages and Arabic is not yet one of those.

  • I can't seem to make a working profile to connect to office 365 on a windows 7 pc with only the mapi cdo runtime version 6.5.8320.0 installed using mfcmapi nor programmatically

    Hi,
    I have been struggling with this for a few days now.
    i have pc where no outlook is installed, where i installed the MAPI CDO Runtime may update (version 6.5.8320.0). i checked in the registry that the default mail provider was set to exchangemapi (HKEY_LOCAL_MACHINE\SOFTWARE\Clients\Mail) .. it is.
    I downloaded the lastest version of mfcmapi, which i believe was the version of december 2013
    but i can't seem to create a profile for office 365 in it. I followed http://blogs.msdn.com/b/dvespa/archive/2013/05/21/how-to-mfcmapi-create-mapi-profile-exchange-2013.aspx and then i changed the properties to what was proposed here http://blogs.msdn.com/b/dvespa/archive/2013/07/15/create-profile-connect-mfcmapi-to-office-365.aspx
    That did not work, i keep getting an error one ore more properties are invalid when i try to use that created profile to connect to office 365 (from within mfcmapi).
    I also changed some of those proposed values to what autodiscover was telling me like setting PR_PROFILE_RPC_AUTH_PACKAGE to RPC_C_AUTHN_ANONYMOUS which should be the value $8000F001 instead of RPC_C_AUTH_NONE (at least i think so)
    I builded a simple program to encrypt my password using CryptProtectData and entered the value using mfcmapi in PR_PROFILE_AUTH_PASSWORD as was suggested in the last page.
    but nothing seems to work, i keep getting wrong configured errors and i'm totally clueless atm. This is supposed to work right on a pc where outlook is not installed ?
    I also tried this on another pc where outlook 2010 is installed and i am able to create the profile there and connect without a problem given that i enter the logon credentials once and let them be remember (they get stored / cached in the windows key store,
    like when using CREDWRITE function) from then on i can connect without a problem.
    also when calling configuremsgservice on the EMS service i created for a new profile in mfcmapi and let the UI show i can see on the pc where outlook is installed in the UI options to enter proxy information however when i do the same thing on the pc
    where only the mapi cdo runtime is installed i do not see any UI option to configure the proxy server information ... is this normal ?
    Hopefully someone can shed some light on what i'm doing wrong or might be wrong.
    Thanks in advance
    Willems Davy

    The window would open and I would get the hourglass cursor suggesting something was happening, but the Apple home page (default from the install) would not load, nor would any other page I tried (google, yahoo, cnn).
    Even though it's about a different application, I'd try the following document with that:
    iTunes 10.5 for Windows: May see performance issues and blank iTunes Store
    (Safari uses the same webkit engine to render web pages as iTunes uses to render the Store pages. So an issue that can cause the iTunes Store to blank can also cause a Safari for Windows application on the same PC to produce blank pages.)

  • I bought an iPhone 5s in China and the maps app is different.  When I go to the US will I be able to use Apple's native app or will I be stuck with this one?

    So I wanted to ask a question that my googlefoo couldn't help me solve.
    I bought an iphone at a reputable electronics market here in China and it is an AT&T model phone.  I bought it at one of the grey market locations because they were sold out elsewhere.  I contacted a friend at AT&T to make sure it is a legit AT&T model.  The phone is great and everything works perfectly including maps.  But maps are done by Autonavi here in China, not Apple.  I downloaded the Mavericks update on my mac and tried some of the new maps features and they wouldn't work with my phone.  That's okay since I live in China now but I'll be going back to the USA soon and I wonder what will happen.  Will it update the app to Apple's native one or stay with Autonavi.  Autonatvi does not have the flyover features and it is not robust in the USA.
    Who can help me out here?  Has anyone purchased a 5, 5c, or 5s in China and gone elsewhere?  Did the maps app change?
    Thank you
    tl;dr my china iphone has autonavi for maps not apple, when I go to the usa will I get the native app?

    I live in China as well and my iPhone5s is the model A1530 I bougth outside China. I have the same problem as Nikatnight with the iPhone while the iPad Air (wifi only) is working like a charm. It must be definitely something related to the carrier since I was abroad few days ago and everything worked well.
    If you pay attention at the source of your maps, you'll discover they are provided by AutoNavi instead of TomTom and make them appear in chinese with their own border interpretation. Queries are only acceppted in Chinese (p.e. if I type in english "Los Angeles International Airport"  it replies it cannot locate it)
    I suppose everything will be fine when you'll be out of censorship....
    Perhaps iOS  Apple Maps are absolutely useless for expatriate in China.
    Use Google Maps instead
    BTW, I'm surprised how much Apple might prostrate towards hard power Governments.... No matter what, money are always on top!

  • When using a personal dropbox account, is it possible to use the mapped drive without downloading all my dropbox files to my hard drive as well?

    When using a personal (not business) dropbox account on my mac book pro, is it possible to use the mapped drive only?  Currently I have dropbox mapped to my computer but it is also saving a redundant copy of the data on my hard drive.  My goal is to pull, edit and save files on the mapped drive only without having a redundant back up of all my dropbox files on my computer wasting valuable storage space.   Any advice out there?  Thanks in advance for your help!

    I don't believe that is accurate, but maybe I am missing something (I am not a Windows user).
    Looking at 2 explanation of how to map a Dropbox as a drive…
    http://lkeng.org/wp/?p=147
    https://www.youtube.com/watch?v=5d8uvseVr5A
    Both of those are linking to the 'local copy' of Dropbox. It is not a true 'network' drive as far as I can see (it still requires the local copy on the PC).
    Another video suggests using another service to mount the Dropbox, but that is not using Dropbox anymore, it is going through Otixo…
    https://www.youtube.com/watch?v=FAIpm2qmglU
    Dropbox does not provide easy to use URL's to mount as a network disk so I don't think this is possible on OS X.
    Dropbox's forum has this too…
    https://www.dropboxforum.com/hc/communities/public/questions/202133795-How-to-ma p-dropbox-as-a-network-drive-on-Mac?loca…
    You may need to examine the Windows computers carefully - if they have Dropbox installed & running then all the files are stored on the local machine in addition to the 'mapped drive'.
    It looks to me like people are 'redirecting' the local copy to appear like a remote disk just so they can address that path on other machines - each PC is being setup the same. You could create aliases on OS X, but it doesn't help move files off the machine.
    Hopefully someone else will contradict me, but I don't think this is how Dropbox works.

Maybe you are looking for

  • Anyone Make Anything Out Of This Crash Log?

    I've been getting crashes today while bouncing. I'll bounce a mix (about a 3 minute pop tune). Then bounce it again minus lead vocals, then about the third bounce, where I turn all the vocals off, I hit bounce and get a beachball, and Logic says it w

  • Data extract from huge table

    Hi, I am extracting data from a table which has more than 25 million records without using any where condition. 45000 records in a file, in multiple files. What is the best way to write the select statement. Thanks, fract

  • How do you restore a phone when it is in recovery mode?

    Tried updating my phone to 7.1.1 and it is now giving me what I think is the screen of death.  I have the iTunes logo and it telling me to plug it in.  Plugged it into my computer and iTunes is telling me it detects a phone in recovery mode and that

  • Newby, CS5, File Structure

    I'm old with Photoshop and new with Video editing. On CS5 Production Premium, Windows. What's the best approach to managing my files/folders? No matter what I set, the system seems to default to ...Documents/Adobe/Premiere/5.0. Can I change this, and

  • Cannot configure RBA to report on deployments to a higher-level collection that flows down to computers in lower collections

    I have been trying to figure out the answer to this RBA question for months and I think the answer is just "you can't do it" but I thought I would ask all of you geniuses... 1)The following collections are setup (based on limiting collections): All S