HashMap , int [][] - key , compareTo override problem , help

i've a hashmap Map<int [][] , Integer> and i want to get the corresponding value for int a[][] from the map.
if i use , map.containsKey(a)
it doesn't compare as required( it doesn't consider order )
so i thought of using class key implementing comparable like this,
class key implements Comparable
          int a[][];
          public key(int p[][])
          {     a=p;     }
          public int compareTo(Object o)
                        key k = (key)o;
               for(int i = 0 ; i < 3 ; i++)
                    for(int j = 0 ;j < 3 ; j++)
                         if(a[i][j]!=k.a[i][j])     return 1;
               return 0;
}now when i create a key ,
key KK = new key(a) // a is int[][]
map.containsKey(KK) doesn't invoke compareTo method itself ..
don't what the problem is.
but when i try . TreeMap it invokes compareTo method
but don't know why , it acts as before when Map<int [][] , Integer> was used.. any idea
Thanx

manishmulani@nitk wrote:
wil the following way of overriding hashcode work??
class key
          int a[][];
          public key(int p[][])
          {     a=p;     }
          public boolean equals(Object o)
               key k = (key)o;
               for(int i = 0 ; i < 3 ; i++)
                    for(int j = 0 ; j < 3 ; j++)
                         if(a[i][j]!=k.a[i][j])     return false;
               return true;
          public int hashCode()
               return a.hashCode();
NO! When doing that, you will get undesirable results. Execute the following lines of code and examine the output:
System.out.println(new int[][]{{1,2},{3,4}}.hashCode());
System.out.println(new int[][]{{1,2},{3,4}}.hashCode());This is better:
public int hashCode() {
  int hash = 1, mutliplier = 1;
  for(int[] row: array) {
    for(int val: row) {
      hash ^= (val * mutliplier);
      mutliplier *= 10;
  return hash;
}(Untested!!!)
ok this will be same if i use TreeMap and implement Comparable<key> and override compareTo() right??Err, yes, more or less. Of course, a HashMap and TreeMap are not the same.

Similar Messages

  • CompareTo override problem

    class Node implements Comparable
              public int id;     
              public int weight;
              public int pred;
              public int ds;
              public Node(int id, int weight, int ds, int pred)
                   this.id = id;
                   this.weight = weight;
                   this.ds = ds;
                   this.pred = pred;
              public String toString()
                   return "" + ds;
                public int compareTo(Object obj)
                 return this.ds.compareTo(((Node)obj).ds); // <---error here     }
    my error is:
    int cannot be dereferenced:
              return this.ds.compareTo(((Node)obj).ds);
    Can anyone help me here. Thanks

    class Node implements Comparable
              public int id;     
              public int weight;
              public int pred;
              public int ds;Ever heard of encapsulation? Why are these public? Bad design, IMO.
    return this.ds.compareTo(((Node)obj).ds); // <---error here
    int cannot be dereferenced:
              return this.ds.compareTo(((Node)obj).ds);It's pretty easy to see, with that hint from the compiler: this.ds is an int, which is a primitive. You can't call compareTo on a primitive. You can, however, write it like this:
    Node other = (Node)obj;
    if (this.ds < other.ds)
       return -1;
    else if (this.ds > other.ds)
       return 1;
    else
       return 0;%

  • Key-Others Trigger (Please help!!!)

    Hi everybody,
    We are trying to restrict the end user from pressing some
    'dangerous' keys, i.e clear block, execute query, even the DOWN
    key causes us problems in some (1 record) blocks.
    I know there is a way to do it using Oracle terminal but it
    seems that we need greater degree of flexibility.
    I certainly don't want to go to every <KEY> trigger on every
    form (block) and put null; statements there. I know from Oracle
    Docs that I'm supposed to use the key-others trigger..
    So here are my questions:
    1.Is there any way to find out which key has been pressed?
    2.Can someone post a sample code of a KEY-OTHERS triggers?
    3.Is there another way to achieve what we need?
    Thanks is advance for any help.
    Mike
    null

    You have two options.
    1) Turn off all keys not wanted. This is what you said
    you did not want to do.
    2) Tun on all keys you want to use by creating a trigger for
    each key. i.e.
    trigger KEY-NXTREC trigger KEY-UP
    NEXT_RECORD; UP;
    Then turn off all keys not explicitly turned on.
    trigger KEY-OTHERS
    NULL;
    ET (guest) wrote:
    : Hope that it may be helpful.
    : Answer :
    : 1. In command line, add debug option so that you may know what
    : trigger is executing.
    : e.g. runform module= userid= debug=yes
    : 2. Sample code for Key-others trigger
    : null;
    : Rgds,
    : ET
    : Mike Braude (guest) wrote:
    : : Hi everybody,
    : : We are trying to restrict the end user from pressing some
    : : 'dangerous' keys, i.e clear block, execute query, even the
    : DOWN
    : : key causes us problems in some (1 record) blocks.
    : : I know there is a way to do it using Oracle terminal but it
    : : seems that we need greater degree of flexibility.
    : : I certainly don't want to go to every <KEY> trigger on every
    : : form (block) and put null; statements there. I know from
    : Oracle
    : : Docs that I'm supposed to use the key-others trigger..
    : : So here are my questions:
    : : 1.Is there any way to find out which key has been pressed?
    : : 2.Can someone post a sample code of a KEY-OTHERS triggers?
    : : 3.Is there another way to achieve what we need?
    : : Thanks is advance for any help.
    : : Mike
    null

  • IE7: How to block F1 key to show windows help in java applet?

    Question
    My applet use F1 shotcut key in each popup dialog(JDialog) to show application
    help, IE6 works correct, but IE7 shows windows help also besides
    applicaiton help.
    By the way, when applet got the focus, the windows help do not popped up
    when press F1 key. Who can help me?
    The owner of the JDialog is sun.plugin.viewer.frame.IExplorerEmbeddedFrame
    which is get by the following code:
    Frame jFrame = null;
    Container f = getParent();
    while ((f != null) && (!(f instanceof Frame)))
    f = f.getParent();
    if (f == null)
    jFrame = new Frame();
    else
    jFrame = (Frame)f;
    } //else

    In my testing, I found out that this works in IE7:
    <body onhelp="return false;">
    But if you call a function that returns false, then it doesn't work, i.e., the following doesn't work:
    function donothing() {
    return false;
    <body onhelp="donothing();">
    In the applet codes, this seems to be a problem only when the dialog owner is IExplorerEmbeddedFrame. When I set the owner to null, then pressing F1 no longer pops up IE help window.
    Edited by: bkyd on May 8, 2008 2:06 PM

  • KeyUp(Event e, int key) not responding

    For some reason the key events, such as "keyUp(Event e, int key)", will only fire after I have first clicked in the applet's window. Any clues as to why this might be happening? I though maybe it was a focus issue, so I tried using "requestFocus()" in my applet initialization, but that didn't work either. Any help is greatly appreciated.

    HERE's the source:
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.Applet;
    public class OLGame extends Applet implements ActionListener, KeyListener
      Image image;
      Graphics offscreen;
      public void init()
        setBackground(Color.black);     
        image = createImage(600,500);
        offscreen = image.getGraphics();
        setSize(600,500);
        this.addKeyListener(this);
        this.requestFocus();          
      public void update(Graphics g)
        paint(g);
      public void paint(Graphics g)
        g.drawImage(image,0,0,this);
      public void actionPerformed(ActionEvent evt)
        // add action events here          
      public void keyPressed(KeyEvent e)
        offscreen.fillRect(0,0,600,500);
        offscreen.setColor(Color.red);
        offscreen.drawString(""+e.getKeyCode(), 25,25);     
        offscreen.setColor(Color.black);
        repaint();
      public void keyReleased(KeyEvent e)
        //empty, but needed for implementing KeyListener
      public void keyTyped(KeyEvent e)
        //empty, but needed for implementing KeyListener

  • Please Help!! I deleted the folder System en Macintosh HD and now when i on my mac it says Disk Error Press Any  Key To Restart Please HELP !!

    I deleted the folder System en Macintosh HD and now when i on my mac it says Disk Error Press Any  Key To Restart Please HELP !!

    Reinstall Mac OS X.
    (59450)

  • HT4623 updated "successfully" to iOS7 on my 4S but now it takes FOREVER to recognize each keystroke - even to type in passcode.  also takes forever to type a single key in text.  HELP.

    updated "successfully" to iOS7 on my 4S but now it takes FOREVER to recognize each keystroke - even to type in passcode.  also takes forever to type a single key in text.  HELP.

    Adjusting the date or time didn't do anything for me either. I'm guessing my two options are to either do the full restore from scratch and not apply any backup ... Or possibly wait for an iOS update that might resolve this issue.
    I'm not that much of an avid twitter user that I need it implemented natively in all my devices - so for now I'll probably value all my game save data, internal settings in apps e.t.c. over that functionality (or over the amount of work it would be to get me back to where I am now after a full wipe). I'll see what happens after the next iOS delta update. I'll reevaluate the full wipe after that if the issue hasn't been resolved

  • My daughter has just bought me an iPad 2 from Dubai and set it all up for me but unfortunately the iMessage function doesn't seem to work. We keep getting messages,when trying to activate it, that there is a network connection problem - help!

    My daughter has just bought me an iPad 2 from Dubai and set it all up for me but unfortunately the iMessage function doesn't seem to work. We keep getting messages,when trying to activate it, that there is a network connection problem - help!

    Thank you both for your responses but my daughter was reassured by the salesman in the iStyle store (official Apple store in the UAE) that iMessages would work but conceded that FaceTime wouldn't. My iTunes account is registered in the uk and my daughter's iPhone has iMessages even though she bought it (and uses it) in Dubai. Can anyone else throw any light on this?

  • I couldn't log into my apple account on my iPad, then i couldn't unlock it resulting in it being disabled, however it's the same as my iPhones password, I then called apple, i was hung up on twice and they said it will cost £70 to fix THEIR problem, help?

    I couldn't log into my apple account on my iPad, then i couldn't unlock it resulting in it being disabled, however it's the same as my iPhones password, I then called apple, i was hung up on twice and they said it will cost £70 to fix THEIR problem, help?

    If you cannot remember the passcode, you will need to restore your device using the computer with which you last synced it. This allows you to reset your passcode and resync the data from the device (or restore from a backup).
    If you restore on a different computer that was never synced with the device, you will be able to unlock the device for use and remove the passcode, but your data will not be present.
    You may have to force iPad/iPod into Recovery Mode
    http://support.apple.com/kb/ht4097

  • IPad syncing problem - HELP!

    iPad sync problem - HELP!  I keep getting this message "...cannot be synced because there is not enough free space to hold all of the items in the iTunes library (additional ...space needed)"  and yet I seem to have plenty of space on the iPad.  This just started today.  I even tried deleting some things to make even more room, but it didn't help.  Any ideas??? 
    I was thinking of restoring, but I've never done it...  should I? 
    thank you!

    Hello florafromnv,
    Welcome to Apple Support Communities.
    The following article addresses how to resolve the issues related to this message:
    iOS: "Not enough free space" alert when trying to sync
    http://support.apple.com/kb/TS1503
    Regards,
    Jeff D.

  • MOVED: KT333 Ultra; fuzzy logic, 1.6xp overclocking problem help !!!!!

    This topic has been moved to Overclockers & Modding Corner.
    KT333 Ultra; fuzzy logic, 1.6xp overclocking problem help !!!!!

    Not that I am an expert o/c but here are some thoughts on the matter.
    My comments are based on my experiences of the KT3 Ultra2 which is basically the same as the Ultra version.
    This mobo does not have the ability to lock the PCI/AGP bus freely from the FSB. However, it does have dividers. At 133 a 1/4 divider kicks in. Above 152FSB the 1/5 divider works, so that at 166 the PCI & AGP buses will be back in sync. If you are o/c your cpu, don't go from 133 to 145, etc since you will be running the PCI/AGP buses further out of whack. Just go to either the mid 150's or to 166 in one jump. The other problem / issue relates to your cpu. From what you say you have one of the old Palominos which are not great o/c's. I would personally o/c your cpu from the BIOS rather than 'Fluffy Logic' which I would tend to stay away from. 
    With a 166FSB cpu a very stable o/c would be 175-177 beyond 180 gets decidedly tricky.
    Hope this helps

  • I accidently deleted my url box at the top of safari. I believe I did this with the command key. Can anyone help me get it back? Thank you in advance!

    I accidently deleted my url box at the top of safari. I believe I did this with the command key. Can anyone help me get it back? Thank you in advance!

    Right click (cntl-click) on the top of the bar and select "customize toolbar".  Drag the default set back in.
    Regards,
    Captfred

  • Itunes keeps closing as soon as i open it and states 'windows has detected a problem' HELP!!!!

    Help!! Itunes keeps closing straight away and message states 'windows has detected a problem' HELP ASAP PLEASE!!!!

    For general advice see Troubleshooting issues with iTunes for Windows updates.
    The steps in the second box are a guide to removing everything related to iTunes and then rebuilding it which is often a good starting point unless the symptoms indicate a more specific approach. Review the other boxes and the list of support documents further down page in case one of them applies.
    Your library should be unaffected by these steps but there is backup and recovery advice elsewhere in the user tip.
    If you've already tried a complete uninstall and reinstall try opening iTunes in safe mode (hold down CTRL+SHIFT as you start iTunes) then going to Edit > Preferences > Store and turning off Show iTunes in the Cloud purchases. You may find iTunes will now start normally.
    tt2

  • Hashmap in Hashmap as Key?

    Can anybofy let me know, what could be the possible disastrous outcome of keeping Hashmap in Hashmap as Key?
    Could it lead to inconsistent behaviour?
    If its not a good idea to use Hashmap as key in a Hashmap what other data structure we can use for the same?
    Thanks,
    Amit G.

    Hello Amit,
    I have a question - "Will the contents of the HashMap, which is the key to your second HashMap, change over a period of time.".
    See sample below -
    import java.util.HashMap;
    import java.util.Map;
    public class Foo {
         private Map<Map, String> mainMP = new HashMap<Map, String>();
         private Map<String, String> one = new HashMap<String, String>();
         public static void main(String[] args) {
              Foo f = new Foo();
         Foo() {
              mainMP.put(one, "SomeStr");
              String str = mainMP.get(one);
              System.out.println("First Time : " + str);
              one.put("hello", "where");
              str = mainMP.get(one);
              System.out.println("Second Time : " + str);
    }When you run the program the result will be -
    First Time : SomeStr
    Second Time : null
    The reason is that the hashCode for a Map object depends on its contents. So Map one will have a different hashCode when it is empty and another one when it has the String "hello". So if you add or remove any object from within a Map, the hashCode will change.
    Having a HashMap as a key (which changes over time) to another HashMap is a sure recipe for disaster.
    If you could tell the scenarion where you are using it, maybe I could suggest a different data structure.

Maybe you are looking for

  • Communication channel reports error after system restart.

    Hello, We have third party adapter Aria installed in our PI 7.1 system and whenever systems is restarted interface is reporting errors in default trace and communication dies. but after we manually activate each time it works properly. Is anyone had

  • Creating a new "root level" folder in Infoview

    In Infoview (XI 3.1 SP6), does anyone know if it is possible (and how) to create a new "root level" folder, to add to the existing ones that are already there? At the root level, is "My favorites", "Inbox" and "Public Documents".  I've been asked to

  • Error Headache

    So I'm done with my portfolio elements and into testing movie everything works fine and now I want to bring this into another swf for preloading and I get this error: ReferenceError: Error #1065: Variable flash.geom::Matrix3D is not defined.     at i

  • Flash 11.6 works, Flash 11.7 does not

    Tried several methods, nothing worked; the video does not start, just keeps black. Firefox uninstallation (and installation ;-), all other plugins deactivated, no installation of ad-plugins, no realplayer ... Used Adobe Flash uninstallation procedure

  • NAC L2 OOB VG ARP, DNS

    I am deploying a NAC 4.7.2 in-house to stage for a customer deployment, the deployment method I used is L2 OOB VG, I configured the switch, managed subnets, and vlan mapping. However, two problems arose: 1. Arp replies from the trusted to the untrust