Java.util.Hashmap doesn't work for a custom object

Hi,
i have created a class named ID. I am trying to test it on a Hashmap, but the the "containsKey" and "get" operations do not work. Every operation of the main method returns as if the ID objects have not been inserted. Ideas?
package swarm.sys.id;
import java.util.*;
import java.io.*;
import swarm.sys.common.*;
import swarm.sys.interfaces.*;
public class ID implements IDInterface, Cloneable, Serializable
    String type;
    int body;
    String id;
    private static int idCounter=0;
    public ID(String type, int body)
      this.type=type;
      this.body=body;
      id=type+Ids.padWithZeroes(body);
    public String getType()
      return type;
    }//getType
    public String getBody()
      return Ids.padWithZeroes(body);
    }//getBody
    public int getIntBody()
      return body;
    }//getIntBody
    public boolean equals(Object o)
      if (!(o instanceof ID))
        return false;
      else
          ID id=(ID)o;   
          return (this.getType().equals(id.getType()) && 
                  this.getIntBody()==id.getIntBody());        
    }//equals
    /* factory method, which produces new IDs and afterwards
     * increments the body part
    public static ID newID(String type)
        return new ID(type,idCounter++);
    }//newID
    //implements deep cloning
    public Object clone()
        return new ID(new String(this.type),this.body);
    }//clone
    public String toString()
      return id.trim();
    }//toString
    public static void main(String[] args)
        Hashtable<IDInterface,String> table=new Hashtable<IDInterface,String>();
        table.put(new ID("PEER_",1),"x1");
        table.put(new ID("PEER_",2),"x1");
        table.put(new ID("PEER_",3),"x2");
        table.put(new ID("PEER_",4),"x3");
        table.put(new ID("PEER_",5),"x3");
        ID id1=new ID("PEER_",1);
        ID id14=new ID("PEER_",14);       
        System.out.println("table.containsKey(new ID(PEER_,1)): "+table.containsKey(id1)); //should be true
        System.out.println("table.containsKey(new ID(PEER_,14)): "+table.containsKey(id14)); //should be false
        System.out.println("table.get(new ID(PEER_,1))"+table.get(id1)); //should be x1
}

You need to override the hashCode() method.
http://www.javapractices.com/Topic28.cjp

Similar Messages

  • Java.util.ProperyPermission does not work for

    Hi again!
    I have some problems with a security.policy file. Its content is provided below:
    grant{
         //Alow the client to connect to any port above 1024
         permission java.net.SocketPermission "*:1024-", "connect";
    permission java.util.PropertyPermission "user.language", "read, write";
    Unfortunately, the java.util.PropertyPermission does not work. I always get the following exception:
    java.security.AccessControlException: access denied (java.util.PropertyPermission user.language write)
    at java.security.AccessControlContext.checkPermission(AccessControlContext.java:264)
    at java.security.AccessController.checkPermission(AccessController.java:427)
    at java.lang.SecurityManager.checkPermission(SecurityManager.java:532)
    at java.util.Locale.setDefault(Locale.java:352)
    at essex.kkarad.cache.daemon.SimplePopulationStrategy.doPopulate(SimplePopulationStrategy.java:41)
    at essex.kkarad.cache.daemon.Populator.run(Populator.java:42)
    Is there any problem with the decleration of the premission? Any ideas?

    Err, this may come as a shock, but it's because you changed the system clock.
    The Timer class works out the absolute time when to next to do something, and when you change the system clock you break that time.
    How much are you changing it by?

  • SMS doesn't work for non-local phone number

    Moved to http://supportforums.blackberry.com/t5/Java-Development/SMS-doesn-t-work-for-non-local-phone-number/...

    Hi iantra123,
    Just make sure you make the SIP-Phone use G711ULAW
    https://supportforums.cisco.com/thread/2074398
    http://www.cisco.com/c/en/us/td/docs/voice_ip_comm/cucme/admin/configuration/guide/cmeadm/cmefac.html
    Kindly rate the post accordingly.
    Regards,
    Kevin

  • Cannot send a null Map key for type 'java.util.HashMap'

    Hi All,
      I am haing an issue with sending data from Server to the client using the AMF Channel.
      Most of the method invocations on the RemoteObject are throwing the following Exception.
    [CODE]
    (mx.rpc.events::FaultEvent)#0
      bubbles = false
      cancelable = true
      currentTarget = (null)
      eventPhase = 2
      fault = (mx.rpc::Fault)#1
        content = (null)
        errorID = 0
        faultCode = "Server.Processing"
        faultDetail = (null)
        faultString = "Cannot send a null Map key for type 'java.util.HashMap'."
        message = "faultCode:Server.Processing faultString:'Cannot send a null Map key for type 'java.util.HashMap'.' faultDetail:'null'"
        name = "Error"
        rootCause = (null)
      headers = (null)
      message = (mx.messaging.messages::ErrorMessage)#2
        body = (null)
        clientId = "22E55FB1-910E-312F-E37A-ED5167139CB0"
        correlationId = "4DB54224-662A-C596-D165-F7C3EBB64DB8"
        destination = "TimeMap"
        extendedData = (null)
        faultCode = "Server.Processing"
        faultDetail = (null)
        faultString = "Cannot send a null Map key for type 'java.util.HashMap'."
        headers = (Object)#3
        messageId = "22E56255-D62F-2ACF-4DA5-CF1E4D6353BB"
        rootCause = (null)
        timestamp = 1266877198902
        timeToLive = 0
      messageId = "22E56255-D62F-2ACF-4DA5-CF1E4D6353BB"
      statusCode = 0
      target = (null)
      token = (mx.rpc::AsyncToken)#4
        message = (mx.messaging.messages::RemotingMessage)#5
          body = (Array)#6
          clientId = (null)
          destination = "TimeMap"
          headers = (Object)#7
            DSEndpoint = "my-amf"
            DSId = "22E53936-7E0E-B21C-C936-EF1078000306"
          messageId = "4DB54224-662A-C596-D165-F7C3EBB64DB8"
          operation = "getMapKey"
          source = (null)
          timestamp = 0
          timeToLive = 0
        responders = (Array)#8
          [0] (com.universalmind.cairngorm.events::Callbacks)#9
            conflictHandler = (null)
            faultHandler = (function)
            priority = 0
            resultHandler = (function)
        result = (null)
      type = "fault"
    [CODE]
    The Spring bean which is exposed as a Remote Object has the following method signature..
    [CODE]
    public String getMapKey() {
            return mapKey;
    [/CODE]
    I am unable to understand why AMF Channel or Blaze DS is treating the String as HashMap !!!
    This was working pefectly fine till yesterday !!
    The version of the BlazeDS i am using is : blazeds_turnkey_3-0-0-544
    and the Flex SDK Version is : flex_sdk_3.5.0.12683
    We recently upgraded to Flex 3.5.0 version earlier we were using 3.3 version
    Thanks
    mars

    Hi All,
    I chcked my server side java beans ( which are managed by Spring) and they are all returning the data property and none of the Keys in the returned hashmaps are null.
    Not sure why this is happening.
    Thanks
    kumars

  • Java 7 update 51 cause the following error: java.util.HashMap cannot be cast to java.awt.RenderingHints

    Since I installed Java 7 update 51 accessing the EMC VNX Unisphere Console cause the following error: java.util.HashMap cannot be cast to java.awt.RenderingHints.
    I rolled back to Apple Java 1.6 -005 now I am getting the following error: plug-in failure.
    I think this is cused by the fact that the EMC console application has been written for java 7 and not java 6. Has anybody faced and solved the "java.util.HashMap cannot be cast to java.awt.RenderingHints." error ?

    Hi Yaakov,
    The error is thrown from the  eclipselink.jar:2.5.1 which is a JPA provider .
    Is the above jar bundled in the Oracle Product you are working upon or was this downloaded from external site ?
    If the jar is bundled with the Oracle Product, go ahead a log a SR with Oracle Support with Toplink product group to drill down on the issue, as the issue is happening internally or thrown by the Eclipselink implementation and we've no control....
    Hope it helps!!
    Thanks,
    Vijaya

  • [BUG]: MakeWritable doesn't work for mac

    I'm trying to use oracle.jdeveloper.refactoring.util.MakeWritableHelper in my plugin, and I found it doesn't work for MAC. The byte code shows it only check the osname for "Windows" and "Linux".
    and some Jdeveloper refactoring feature failed due to can't make file writable, they may also related to this class.

    My MAC version is OSX 10.5.4.
    I don't have a stacktrace. It just fails silently.
    You can easily reproduce this bug by reformat a readonly file.
    Here is the code I reverse engineered from oracle.jdeveloper.refactoring.util.Util.java:
    public static boolean setReadOnly(java.net.URL url, boolean readOnly)
    boolean ret = false;
    java.lang.String cmdarray[] = null;
    java.lang.String platformPathName = oracle.ide.net.URLFileSystem.getPlatformPathName(url);
    java.lang.String osName = java.lang.System.getProperty("os.name", "");
    if(osName.startsWith("Windows"))
    cmdarray = (new java.lang.String[] {
    "ATTRIB", readOnly ? "+R" : "-R", (new StringBuilder()).append('"').append(platformPathName).append('"').toString()
    else
    if(platformPathName.equalsIgnoreCase("Linux"))
    cmdarray = (new java.lang.String[] {
    "chmod", readOnly ? "u-w" : "u+w", (new StringBuilder()).append('"').append(platformPathName).append('"').toString()
    if(cmdarray != null)
    java.lang.Runtime runtime = java.lang.Runtime.getRuntime();
    try
    java.lang.Process process = runtime.exec(cmdarray);
    if(process.waitFor() == 0)
    ret = (new File(platformPathName)).canWrite();
    if(ret)
    oracle.ide.model.Node node = oracle.ide.model.NodeFactory.find(url);
    if(node instanceof oracle.ide.model.TextNode)
    oracle.ide.model.TextNode textNode = (oracle.ide.model.TextNode)node;
    textNode.isReadOnly();
    catch(java.io.IOException e)
    e.printStackTrace();
    catch(java.lang.InterruptedException e)
    e.printStackTrace();
    return ret;
    }

  • How can I add a new Template to My Templates in Pages? I've read most of the discussions on the subject but it doesn't work for me. By the time I reach the Templates folder, I only see templates for Numbers and not for Pages. Need help, please.  Thanks

    How can I add a new Template to My Templates in Pages? I've read most of the discussions on the subject but it doesn't work for me. By the time I reach the Templates folder, I only see templates for Numbers and not for Pages. Need help, please.  Thanks

    Si vous avez utilisé la commande Save As Template depuis Pages, il y a forcément un dossier
    iWork > Pages
    contenant Templates > My Templates
    comme il y a un dossier
    iWork > Numbers
    contenant Templates > My Templates
    Depuis le Finder, tapez cmd + f
    puis configurez la recherche comme sur cette recopie d'écran.
    puis lancez la recherche.
    Ainsi, vous allez trouver vos modèles personnalisés dans leur dossier.
    Chez moi, il y en a une kyrielle en dehors des dossiers standards parce que je renomme wxcvb.template quasiment tous mes documents Pages et wxcvb.nmbtemplate à peu près tous mes documents Numbers.
    Ainsi, quand je travaille sur un document, je ne suis pas ralenti par Autosave.
    Désolé mais je ne répondrai plus avant demain.
    Pour moi il est temps de dormir.
    Yvan KOENIG (VALLAURIS, France)  mercredi 23 janvier 2011 22:39:28
    iMac 21”5, i7, 2.8 GHz, 4 Gbytes, 1 Tbytes, mac OS X 10.6.8 and 10.7.2
    My iDisk is : <http://public.me.com/koenigyvan>
    Please : Search for questions similar to your own before submitting them to the community

  • Dynamic versioning plugin tag doesn't work for Netscape using 1.4.1_01?

    When I use dynamic versioning for plugin, for example:
    <EMBED
    type="application/x-java-applet;version=1.4.1_01"
    >
    It doesn't work for netscape 7. Although 1.4.1_01 was installed on the machine, the applet was not able to be loaded. Plugin was not found.
    Anything wrong with the tag? It is OK for 1.4.1
    Thanks

    When I use dynamic versioning for plugin, for
    example:
    <EMBED
    type="application/x-java-applet;version=1.4.1_01"
    >
    It doesn't work for netscape 7. Although 1.4.1_01 was
    installed on the machine, the applet was not able to
    be loaded. Plugin was not found.
    Anything wrong with the tag? It is OK for 1.4.1
    ThanksI lost alot of sleep over this!
    I finally got it to "seemingly" work
    but by NOT using 1.4.1 attribute..
    See my HTML example
    http://hyperbyte.ab.ca/JavaZone/
    While it doesn't work with the 1.4.1
    attribute it does work with Netscape
    Good Luck!
    Sincerely:
    Tony Swain
    Senior V.P. of Software Development Hyperbyte inc.
    http://www.hyperbyte.ab.ca
    Netscape DevEdge Champion Devs-Java Newsgroup
    snews://secnews.netscape.com/netscape.devs-java

  • The wifi at my school isn't very good. And I can't send iMessages through it. It works for some apps like score center and my radar app, but doesn't work for other apps like clash of clans and iMessage. How can I get it to work on that  wifi network

    The wifi at my school isn't very good. And I can't send iMessages through it. It works for some apps like score center and my radar app, but doesn't work for other apps like clash of clans and iMessage. How can I get it to work on my school wifi. I have an iPhone 4S on AT&T and iOS 7.04

    In a roaming network, your "main" router is the device that would require port mapping/forwarding to be configured in order to access the IP camera from the Internet. This router is also the one that would be provide the private IP address for the camera which you will want to be a static one.
    So as you described your network, the IP cameras should be getting an IP address or you assigned it a static one and this is the address that you would enter in the Private IP address (or equivalent depending on the router used) field when setting up port mapping.
    If you are not able to access this camera from the local network, then this should be troubleshot first.

  • With my i phone 4 , the Push notifications doesn't work for apps like (fb viber , whatsapp etc ) it only works for the official apps like message  even when im using the phone, has  this probleme with the iOs 6.0.1 and also with the iOs 6.1

    With my i phone 4 , the Push notifications doesn't work for apps like (fb viber , whatsapp etc ) it only works for the official apps like message  even when im using the phone, has  this probleme with the iOs 6.0.1 and also with the iOs 6.1

    This isn't an issue. Notice the screen prior to the one that shows usage has an iCloud section and a Manage Storage button. For this button to activate ios needs to download a few kb from icloud. Switching back to this screen forces ios to download those few kb.

  • Push notifications doesn't work for apps like (fb viber , whatsapp etc ) iOs 6.1

    With my i phone 4 , the Push notifications doesn't work for apps like (fb viber , whatsapp etc ) it only works for the official apps like message  even when im using the phone, has  this probleme with the iOs 6.0.1 and also with the iOs 6.1

    Sorry, I've forgotten the actions done.
    I've restarted the iphone, and I've recovered a previous backup.
    Thanks.

  • How can I upload a video from my PC through I tunes to camera roll on my iPhone? Is there an app or format of specific video supported? Sync from photos include video doesn't work for me.

    How can I upload a video from my PC through I tunes to camera roll on my iPhone? Is there an app or format of specific video supported? Sync from photos include video doesn't work for me.

    download the new you tube apps in i tunes, in os6 just pick a video in the photos apps and select share, the old you tube app icon will appear

  • I've bought an app called WhatsApp but I was not told that app doesn't work for ipod. So I would like to know how to turn back and get my money back.

    I've bought an app called WhatsApp but I was not told that app doesn't work for ipod. So I would like to know how to turn back and get my money back.

    Did you fail to look at the requirements before purchasing?
    All sales are final.  You can try contacting itunes support and asking for an exception

  • Apache Sling JCR Resource Resolver doesn't work for the anchor tags which is been rendered through j

    Certainly I realized that Apache Sling JCR Resource Resolver doesn't work for the anchor tags which is been rendered through jquery or javascript.
    e.g.
    In Felix Console , in Apache Sling JCR Resource Resolver configuration I have added following mapping.
    /content/myproject/-/
    So If any anchor tag is there like <a href="/content/myproject/en.html"> click me </a> then it will be mapped to "/en.html" automatically.
    But the problem is there in following scenario.
    I have an anchor tag as follows.
    <a href="#" id="test"> click here </a>
    And I am assigning the href to anchor through JQUERY.
    <script>
    $("#test").attr("href","/content/myproject/en.html");
    </script>
    Ideally this should have been mapped to "/en.html".
    But it is not mapping to "/en.html". It still shows "/content/myproject/en.html".
    How to resolve this.
    Thanks,
    Sai

    In a servlet you have access to the resourceResolver so if you know which attributes contain links then it's relatively easy to apply resourceResolver.map to those links.
    Your challenge is clearly how do you know which attributes are links and which aren't. Its is the same challenge that makes parsing the response and rewriting it on the way out difficult - the JSON doesn't have any semantic meaning so how do identify which attributes require rewriting. There really is no good answer ot that question in my experience - all the options have down sides.
    Create some convention - all attributes matching this pattern X get mapped before being converted to JSON (could be attributes whose name ends in link, or it could a convention applied to the value of the attribute - if the attribute is a string that starts with /content apply the resource resolver mapping. In this case you have train your developers to follow this convention which is the down side.
    Create some configurable list of attribute names that require mapping. This is brittle, requires training and is easy to break.
    Implement a client side version of the resource resolver mapping. It wouldn't be as full proof as server side mapping (because that takes into account but you could make it work for simple logic like stripping of /content/site/en. If ou are just trying to solve the simple version of this issue - stripping off the top of the repository path this might be your best option.
    Not worry about it and set up Apache 301 redirects that catch any long URLs and redirect them to short URLs (so configure apache to look for any URL matching /content/site/en and strip off /content/site/en and do a 301 redirect to the shortened URL. You end up with a lot of extra HTTP request because of all the 301s but it would work (I wouldn't recommend this option - but it is possible).

  • HT201263 Unable to update, restore or recover. Slider doesn't slide and number pad doesn't work for passcode. What next? Worked last night . Battery charged. When I push Home button I get my backgroung but can't slide slider. Device is recognized by iTune

    Unable to update, restore or recover. Slider doesn't slide and number pad doesn't work for passcode. What next? Worked last night . Battery charged. When I push Home button I get my backgroung but can't slide slider. Device is recognized by iTunes.Help! Thank you.

    Besweet, I'm having the very same problem with 60GB colour which was bought new and worked for 6 months before suddenly just not being recognised by PC. I hadn't changed anything at all.
    I've followed all troubleshooting advice and reinstalled and updated iTunes and iPod updater software but all troubleshooting routes seem to hit the dead end of either the need to access the iPod via the PC (which isn't possible as it's not showing up at all) or the iPod in disc mode stuck at "ok to disconnect".
    It's still under 1yr warranty so will have to take to a dealer.
    I'm sorry that's not much help for you but at least you know it's not a unique problem.
    PC   Windows XP  

Maybe you are looking for

  • Does Multipoint Server 2012 Support Remote Connections?

    I'm currently running Server 2008 R2 Foundation, and am considering an upgrade.  I originally thought I'd move to 2012 R2 Essentials, but found that it only allows 2 concurrent users, and RDS is not available (what a joke!).  Anyway, someone suggeste

  • Need information on workload volumes being handled in EBS

    Hi , I have received a mail from my client to produce the below information . How do i calculate it if you can help me find the below information would really be appreciated. Please provide the current demand on the system in terms of workload volume

  • Google Chrome and Firefox won't open any sites. Internet explore can.

    Internet Explorer will run any sites. After installing google chrome and firefox its opens the browser but then when i enter a site, any site, it just wont go... It's not giving me an error message... i push the "enter" key and the busy locator, the

  • How to connect to a web service??

    I am banging my head on how to produce the appropriate code to connect to a web service I created locally. I have a local web service: http://localhost:8500/cfc/getprojects.cfc?wsdl I am trying to figure out how to write a correct <mx:WebService> to

  • Good Eveing!:)

    I´ve got a question, i upload my first website this evening. Than i want to change my guestbook in adobe muse. when i was finish, a message says me, the file can´t be saved.. And then Adpobe muse say: Error cod: 3123, the file can´t be saved. Now my