Custom key in Hashtable (or HashMap)

I have built a custom object to be used as a key in a Hashtable. However, even though I provided an implementation of hashcode() and equals(), two key objects that compare equally do NOT locate the same value in the Hashtable. I either do not understand how this is supposed to work or there is a bug. I have JDK 1.3.1.
I hate it when things don't work the way I think it should! Why doesn't this work? ANy ideas how to accomplish this?
public class TransitionKey {
private String stateID;
private String nextStateID;
private String hashKey;
/** Creates new TransitionKey */
public TransitionKey() {
public TransitionKey(String stateID, String nextStateID) {
this.stateID = stateID;
this.nextStateID = nextStateID;
hashKey = stateID+nextStateID;
public TransitionKey(int stateID, int nextStateID) {
this(String.valueOf(stateID), String.valueOf(nextStateID));
public String getStateID() {
return stateID;
public String getNextStateID() {
return nextStateID;
public boolean equals(Object obj) {
TransitionKey other;
if (obj instanceof TransitionKey)
other = (TransitionKey) obj;
else
throw new IllegalArgumentException("Only objects of type " + this.getClass() + " are supported.");
return (other.getStateID().equals(this.getStateID()) && other.getNextStateID().equals(this.getNextStateID()));
public int hashcode() {
return hashKey.hashCode();
public String toString() {
return "(" + getStateID() + "," + getNextStateID() + ")";
public static void main (String [] args) {
TransitionKey one, two;
one = new TransitionKey(10,8);
two = new TransitionKey(10,8);
System.out.println("Objects are: '" + one + "' and '" + two + "'.");
System.out.println("Keys " + (one.equals(two) ? "" : "do NOT ") + "match");
System.out.println("Hashcode test: " + (one.hashcode() == two.hashcode() ? "PASS" : "FAIL"));
java.util.Hashtable tbl = new java.util.Hashtable();
tbl.put(one,"You found me!");
String output = (String) tbl.get(one);
System.out.println("Result using original key: " + output);
output = (String) tbl.get(two);
System.out.println("Result using duplicate key: " + output);
boolean keyTest = tbl.containsKey(two);
System.out.println("Test for duplicate kay in hashtable: " + keyTest);

I believe you don't quite have the right understanding
of how this works. It's not the contents of an object
that allow it to be found in the hashtable, but the
exact object itself.
You have created objects one and two. They have the
same content but are unique objects. You will not be
able to find the string associated with one by trying
to get two.
You can see this by changing one line, instead of
two = new TransitionKey(10,8);try ...
two = one;After that, you'll see that you have found the string
associated with one when you get two. That's because
one and two are now the same object.
So, to get a string associated with two, where two is
unique, you'll have to put two into the hashtable.
I hope this is clear.This is absolutely false. Below is an example using strings that shows this. I am a little confused though, because I have been playing with your class and it is not working the way that I understand maps to work. I'll post again when I have played around some more.
import java.util.HashMap;
public class StringTest {
     public static void main (String [] args) {
          String one = new String("a");
          String two = new String("a");
          HashMap map = new HashMap();
          System.out.println(1);
          map.put(one,"You found one");
          System.out.println(2);
          System.out.println("Result using duplicate key: " + map.get(two));
          System.out.println(3);
          System.out.println("Result using original key: " + map.get(one));
}

Similar Messages

  • How to use standard function keys as custom keys

    how to use standard function keys as custom keys.
    i have encountered that problem while developing a screen, there i'm supposed to use standard function key F2 ( which actually meant for choose) for clearing the screen fields where the cursor is present and f1 for saving data that entered in screen fields, etc...
    kindly help me out.

    Hi ,
    Solution to use SAP reserve function keys F1 .. F4 (mostly this requirement comes up for RF screens) can be acheived by assigning your new Function code using the Menu path Utilities --> F key Consistency in the Menu Painter (SE41) . Once you assign your cutom function code to the standard Fn keys the only remaining step is to make sure that you set a curson on any of the field on sceen by using the Key Word "SET CURSOR" .
    If you dont use the key word SET CURSOR in the PBO of the screen then you might not see any response for F4.
    Thanks

  • Jax-ws 2.1 - problems returning hashtable and hashmap

    Hi,
    We're developing a set of applications that communicate via web services.
    The company decided that to do this we should use jax-ws 2.1.
    Everything is going ok, its really easy to use, except for a web method that returns a java.util.Hashtable.
    In the endpoint there's no problem, it compiles and deploys to a tomcat 5.5 without a problem.
    The client can access the wsdl via url, download it and create the necessary files (we use netbeans 5.5 for this).
    We can invoke the method getConfig without a problem, but the object returned only has the java.lang.Object 's methods, not the java.util.Hastable 's .
    Endpoint:
    package xxx.cdc_pm_i;
    import java.util.Hashtable;
    import javax.jws.WebMethod;
    import javax.jws.WebParam;
    import javax.jws.WebService;
    import javax.xml.bind.annotation.*;
    @WebService()
    public class cdc_pm_i{
    @WebMethod
    public Hashtable getConfig() {
    Hashtable<String,String> config = new Hashtable<String,String>();
         config.put("1","1");
         config.put("2","2");
    return config;
    Client:
    try { // Call Web Service Operation
    xxx.CdcPmIService service = new xxx.cdc_pm_i.CdcPmIService();
    xxx.cdc_pm_i.CdcPmI port = service.getCdcPmIPort();
    // TODO process result here
    xxx.cdc_pm_i.Hashtable result = port.getConfig();
    } catch (Exception ex) {
         ex.printStackTrace();
    I'm fairly unexperienced in Web Services and i have no idea why this works for any kind of return object (as long as its serializable) and has this problem with hashtables and hashmaps.
    Any idea on how to solve this?
    Thanks in advance,
    Rui

    Didn't find the solution for this, but any object that contains an Object in its methods / attributes had the same problems, so i just built my own table that only supports Strings and the problem was solved.
    If anyone knows why i had this problem and wants to share a solution, please do so.

  • Dynamic configuration : possibility of adding custom Key?

    hi experts,
    is it possible that i can add a new custom key like for example
    namespace : http://sap.com/xi/XI/System/ERROR    
    key : ERRORDESC
    and put it inside the Dynamic configuration during a mapping and then use it further?
    or are we limited to the use of ONLY standard key pairs?
    Thanks in advance.
    Regards,
    Amol

    Yes, is possible.
    Take a look here:
    http://wiki.sdn.sap.com/wiki/pages/viewpage.action?pageId=95093307
    http://www.sdn.sap.com/irj/scn/index?rid=/library/uuid/00a7ba12-e7cd-2b10-d589-e52b11346f77

  • T030 - custom key for account determination

    Dear expert,
    according to your opinion would it be possibile to create a custom key for account determination.
    (f.i. ZGBB as a copy of GBB).
    Thank you in advance.
    Fuffo.

    Hi
    You can create new transaction keys for conditions (like delivery costs etc) but regular transaction keys like GBB - I  think not possible.
    Thanks
    Edited by: Praveen Raghavendra on Apr 3, 2009 7:26 AM

  • Custom Key JPA Generator

    Hi all,
    Using CE 7.1 is possible to define a GENERATOR for a Custom Key on CAF Business Object?
    Best regards
    Isaías Barroso

    Hi,
    CAF does not have any key generator.
    What you can do is, you can create a utility DC of java type. Create a Key Generator class that uses SAP's unique ID generator classes.
    com.sap.guid.GUIDGeneratorFactory
    com.sap.guid.IGUIDGenerator
    Method to get the key will look like
    public String getUUID() {
            return this.generator.createGUID().toHexString();
    Now use this class in your caf project to generate unique keys.
    Hope this helps,
    Ashutosh

  • Import custom Key Commands from InDesign CS6 to InDesign CC

    How can I import my custom Key Commands from InDesign CS6 to InDesign CC?

    [Moving the thread to the InDesign Forum]
    While the best practice is to recreate any customizations you made from previous versions to the new version to prevent any hiccups, you can certainly try copying the .indk file from the V8 (InDesign CS6) folder to the V9 (CC) folder.
    Launch InDesign CS6, Edit > Keyboard Shortcuts > create a new set with all your custom keyboard shortcuts
    Launch InDesign CC, Edit > Keyboard Shortcuts > create a new set with the same set name as existed in CS6 but make no modifications
    Locate and copy the [set name].indk file in version 8 and replace it in version 9
    Repeat the above step for any custom sets you made
    Here's the path to locate the .indk file
    Windows Vista and Windows 7 & 8
    Users\[username]\AppData\Roaming\Adobe\InDesign\[Version]\[Language]\InDesign Shortcut Sets
    Mac OS
    Users/[username]/Library/Preferences/Adobe InDesign/[version]/[language]/InDesign Shortcut Sets
    Please take a look here for more info: http://help.adobe.com/en_US/indesign/cs/using/WS668BC5E2-1E1A-4e75-A69A-44A787B4A5FAa.html #WS57E36B38-B2EB-4255-BAB5-19CCCB4319BFa
    Try it out and let us know if this helps. Thanks!

  • ArrayCollection with custom keys

    Hello!
    Is it possible to have an Array or ArrayCollection with 'custom' keys?
    e.g.
    myCollection['name']['first']
    myCollection['name']['last']
    myCollection['age']
    myCollection['address']
    etc...
    AS3 always forces an index-like key: myCollection[0]['name']['first'], myCollection[1]['name']['last'], myCollection[2]['age'] etc.
    Thank you!

    ArrayCollections are basically indexed arrays wrapped in another class. Can't get around that. How about using the dictionary class?
    http://livedocs.adobe.com/flex/3/langref/flash/utils/Dictionary.html
    If this post answers your question or helps, please mark it as such.
    Greg Lafrance - Flex 2 and 3 ACE certified
    www.ChikaraDev.com
    Flex / AIR Development, Training, and Support Services

  • Problem regarding modeled BO custom key prefix

    Hello,
    I have created some business objects (CE 7.11) and renamed the table names in persistency page (from TMP prefix to MYCUSTOM prefix).
    After that I set the appropriate preference in my developer studio (default table name prefix) to MYCUSTOM. All tables from now are created with the correct prefix instead of "TMP".
    But when I set a field of an "old" table the attribute "custom key" the prefix of the newly created index will still be "TMP" And there seems to be no way to rename the prefix to "MYCUSTOM". Only when I set the custom key within a table, which is created after setting the correct preference in the developer studio it works and the prefix of the index is correct.
    Anybody out there who can help me with this issue?
    Thanks ahead,
    Bernd

    The only way to solve this issue was re-creating the table.

  • How can I get keys from Hashtable in the same order?

    Hello, everyone.
    I have a Hashtable containing key-value pairs, I need to get the keys in the same order as I use
    method put(key,value) to save the key-value pairs. But I can only find Hashtable.keys() to fetch the keys in form of Enumeration and when retrieve the keys from the Enumeration,they are not in the original order!
    The following is my code:
    Hashtable ht = new Hashtable();
    ht.put("Name","Harry Bott");
    ht.put("Gender","Male");
    ht.put("Age","25");
    String[] Items = new String[ht.size()];
    Enumeration e = ht.keys();
    int i = 0;
    while(e.hasMoreElements()) {
    Items[i++] =(String)(e.nextElement());
    The Items contains the keys but they are not in the original order.
    Does anyone know how to get the keys from a Hashtable in the same order when they're put?
    Thank you!

    yeah, another solution is to stored keys on a Collection at the same time you put them on the HashMap with its values.
    Then when ur going to retrieve objects from the Map u iterate the Collection that has the ordered keys and use them.

  • Multiple values for one key in hashtable k, v

    So, I know that java.util.hashtable (as of Java 1.5) uses separate chaining to handle collisions. What I want to know is how to get a certain value somewhere in that bucket if they all share a common key? Javadoc says I have to search it sequentially but doesn't say how.

    OK, there's a lot of confusion on here for such a short thread :-)
    Firstly, HashMaps pick which "bucket" to store your object in based on the hash value of your object (see Object.hashCode()). However, the actual object equality test (applied to the keys during a search) is based on Object.equals(). Therefore which bucket your object is in is irrelevant - the bucketting concept is just used as a way of quickly locating a subset of all the keys in the map which might match your search value. There could very well be just a single bucket in a map and it wouldn't change its logical behaviour.
    This statement: "any Map including Hashtable, can only have a single (key,value) pair" is poorly worded. What it should say is that for any given key, a map can only hold a single value.
    Really, you don't need to think about the internal structure of maps (i.e. buckets, etc.).
    If you want to store multiple values for any given key, then make your value a list (java.util.List) and store your multiple real values inside that list.

  • How to get the key value of a HashMap?

    Hi,
    I have a HashMap which obviously has key/value pairs. e.g. 1=3, 2=6 etc. I can get the value by using the method xxx.get(key), but I want to be able to get the value of the key. For example, when I have the value 3 I want to be able to get the value of the key that identifies it, in the example above it would be 1.
    Is there a way to do this.
    I'd appreciate any help.
    Thanks,
    Chris

    A HashMap guarantees unique keys, but not unique values. In the following situation:
    a=2
    b=5
    c=2
    If you wanted to do a lookup based on the value, what would your lookup of 2 return? a or c?
    At any rate, if you can guarantee that your values will be unique, you could always fill a second HashMap while filling the first; the second HashMap would simply have the original values as the keys, and the original keys as the values.

  • Designer/Custom keys for MacBook Pro???

    Does anyone know of any companies out there that make custom or designer keys that fit the MBP? Maybe glass? Aluminum?
    Bryan

    I think it's a nice idea although those two materials are not so practical I think. Glass is heavy and aluminum keys may damage the screen. I would be very satisfied with a color matched keyboard in the same material however.

  • Custom key binding/macro

    Does anyone know of a way to bind/macro a particular key (e.g., "/" or "+") to omit it's normal function and instead paste custom text of your choice (e.g., "roger that") without using a third party program to do so? If a third party program is necessary to create the binding/macro, the only stipulation is that the key binding/macro must work without the program that created it open/running. Thanks ahead of time!

    and a JPanel with an array of DataCells (extends JLabel). Use a JTable, it supports navigation using the arrow keys.
    Here is a simple example with InputMaps and ActionMaps:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class PanelActions extends JFrame implements FocusListener
         LayoutManager layout;
         public PanelActions()
              layout = new GridLayout(0, 10);
              JPanel  panel = new JPanel( layout );
              setContentPane( panel );
              Action rightAction = new AbstractAction()
                   public void actionPerformed(ActionEvent e)
                        JComponent c = (JComponent)e.getSource();
                        c.transferFocus();
              for (int i = 0; i < 30; i++)
                   String text = String.valueOf(i);
                   JLabel label = new JLabel( text );
                   label.setFocusable( true );
                   label.addFocusListener( this );
                   panel.add( label );
                 InputMap im = label.getInputMap(JLabel.WHEN_FOCUSED);
                   KeyStroke right = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0);
                   im.put(right, "right");
                   label.getActionMap().put(im.get(right), rightAction);
         public void focusGained(FocusEvent e)
              JLabel l = (JLabel)e.getSource();
              System.out.println(l.getText());
         public void focusLost(FocusEvent e) {}
         public static void main(String[] args)
              PanelActions frame = new PanelActions();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

  • Aluminum keyboard - customizing keys

    Does anyone know of a way to make the F13 to F15 keys the volume keys with one of the (newer) aluminum keyboards? I have turned off the default keys in system preferences so that I can use the "normal" F functions (rather than dashboard, brightness, etc.), but the system preferences keyboard pane doesn't seem to let me reassign the volume keys to whatever function keys I want. This is very frustrating and makes me miss my old keyboard. I have tried a shareware program called "Controller-Mate" but it seems like something that should be built-in to OS X. Any suggestions?

    Many of us have had the same problem - a sad limitation to an otherwise nice keyboard. Come on Apple - surely you can do better!!

Maybe you are looking for