Why "boolean equals (Object obj);" the fire only once?

In the code below, I add 4 items to "db", but "equals()' in KjPair method, only fires once. Why?
.....
Set<KjPair> db = new HashSet<KjPair>();
db.add(new KjPair(1, 9));
db.add(new KjPair(2, 8));
db.add(new KjPair(8, 2));
db.add(new KjPair(4, 6));
System.out.println("db length --> " + db.size());
....

    static class KjPair {
        int kj1, kj2;
        KjPair(int a, int b) {
          this.kj1 = a;
          this.kj2 = b;
        }

      @Override
      public boolean equals(Object obj) {
        KjPair pair = (KjPair) obj;

        if((this.kj1 == pair.kj1) && (this.kj2 == pair.kj2)) return true;
        if((this.kj1 == pair.kj2) && (this.kj2 == pair.kj1)) return true;
        return false;
      }
      @Override
      public int hashCode() {
        System.out.println("----hashCode()---");
        return 1;
      }
}
My fundamental data structure is a coupling of two characters where (A-> B) is the same as (B-> A).
My problem is that my text input files are very large and very crowded, and each character may be about 2000.
Some pairings could be repeated a hundred times.
For example:
A B
B A
J K
Y - Z
You must create a set of size 3.

In the above code, I get conflicting information.
The size of "db" is correct. Even if I added 4 points, the size of the "db" is 3.
But 'equals()' is triggered only once.
I expect this fire 3 or 4 times.

My problem is more complex. This code is a complete disaster and I'm completely stuck.
I need to start by understanding why 'equal()' is triggered only once.
I punted implemented 'hashCode()', but it never take a shot anyway. Until he does, I will focus on "equals().

Thank you.

hunter9000 wrote:
Must override hashCode() whenever you override equals(), such as when you use your objects in a collection based on the hash, who you are. My suggestion is to give a real implementation hashCode() and then see if you still have problems with equals().

Ironically, the "return 1" hashCode() he provided here (which, while providing a correct behavior, will lead to slow HashMaps and HashSets) will ensure that he does not see the behavior he complained, while a good hashCode() has a high probability of causing said behavior - which, in itself, is good and desirable.

A good hashCode() means fewer calls equals(), that is pretty much the whole point from hashCode().

Tags: Java

Similar Questions

  • "selection of object by the path only" in Indesign?

    Hi, I have just changed to cs4 to 5.5 and can't seem to select an object, if it is another, even if the top element of a 'none' was complete. I know that I can hold cmd and select "via" objects but in cs4, I didn't need to do it as long as the top item had no fill. This preference can be enabled/disabled through the "selection of object by the path only" checkbox in illustrator, but I can't seem to find it in Indesign. Maybe I'm lazy who want to simply do not press the cmd button but it's just annoying the hell out of me for any clarification would be much appreciated.

    Ant.

    Hey Ant,.

    You use the 'Frame' Rectangle tool or the tool 'Rectangle '? I find that I selected the 'Frame' Rectangle tool, it will always be the selected object, even if it has no fill; using the "Marquee" tool, if it has no fill, you can select the objects below it without going through CMD-click.

    Hope that helps,

    See you soon!

    Mikey

  • How to rotate the image only once

    Hai, I am very new in the development of blackberry applications. I need an image that need to be done rotate 360 degrees once only. I see so many references here and I know that there is a thread that discuss it, but I can't find the right one.

    Thanks in advance.

    You asked a single rotation - "how to rotate the image only once.

    There is no standard API that provides a rotating image permanently using standard features of BlackBerry.

    The usual way to display animations is demonstrated in this article.

    http://supportforums.BlackBerry.com/T5/Java-development/display-an-animated-GIF/Ta-p/445014

    If you can prepare your animation and package with your application, it will be much easier and more effective. Do you know what pictures you're going to turn?

  • Acrobat WillClose event fires only once

    Hello

    I wrote a script to the folder (in JavaScript) level that contains a custom Save function which is triggered at the level of the document with the WillClose event. However, I have noticed that this script is called only once. To be more precise, I have a function that validates the required fields until the document is saved, and if not all required fields are filled, an alert is displayed to inform the user of the present. After that, the dialog box normal to save changes coming. If "Cancel" is selected to return to the document and fill in the required fields, the WillClose event fires again when the document is about to be closed. Is there a way to get around this, or it's just the expected behavior in Acrobat for this scenario?

    Any advice on this matter is greatly appreciated.

    Thank you

    I noticed also that at the time. I think it's a bug of more than "whereas behaivor. You should report it here:

    Adobe - feature request/Bug Report Form

  • MapListener to react on the updates of the entries only once.

    I'm trying to use a MapListener to react only on a change of entry once the entire cluster. The cache used is a NearCache.

    I tried adding the MapListener on the BackingMap by using the following:
              NearCache cache = (NearCache) CacheFactory.getCache("MyCache");
              NamedCache backingCache = cache.getBackCache();
              backingCache.addMapListener( new MyMapListener, new MyFilter(), true);
    However I noticed that the earpiece of the card receives events on 2 nodes. I guess that's because the NearCache is configured to be always 1 backup and therefore a change to an entry that happens in 2 places. Is there another way to do this?

    Best regards
    Jan

    Hi Jan

    The listener to support card receives the events on a second node if the object is transferred to this node for the repartitioning. For example, if you do a put option, you will see an input, inserted on the primary only event. After a while, if the partition is moved to another node (new primary), you'll see a deleted on the old primary input event and an evnet entry inserted on the primary again.

    If you need to distinguish between user initiated events and internal consistency initiated events hen see the following code example.

    http://coherence.Oracle.com/display/COH35UG/AbstractMultiplexingBackingMapListener+class+listing

    Paul

  • run the trace() only once within a function of frame of entry?

    I have a frame event enter and a function of execution of this event, I place a trace statement within the function and the scene is running at 25 fps.

    My problem is how do you trace statement run once only? Since it have really annoying when the output panel keep retracing the same and slow down my swf...

    Thanks in advance

    outside your function

    var alreadyDone:Boolean

    inside your listener function

    {if(!alreadyDone)}

    alreadyDone = true;

    trace (...);

    }

  • How can I make my address book show each address of the contact only once?

    my address book shows all e-mails from each contact-5 emails a one touch means that the address will show 5 times

    Well, I think that it is up to you to sort your address books, locate and delete duplicates and decide which of your many address books, you want any particular Contact should be stored in.

    There are modules to help with this, but even with this help, it is quite tedious to choose between multiple entries and decide which are most comprehensive and up to date. If duplicates became spontaneously, then you may have something horrible going on, and I will seek to export data, to delete the address book assigned and recreate by importing the exported data.

    In TB38, the Contacts Sidebar has a new option 'All address books' which includes all your address books in a virtual composite book. This simplifies the search for those who do not know or remember what book they were adding a Contact.

    Under "All address books", you should be able to select any single address book and therefore only see the entries in it. Of course, if you have multiple instances of a Contact in an address book, is what you will see. It just presents what it contains.

  • I need to delay the game only once.  My code runs to each loop.

    Hello

    I am new to Flash.  I can't decifer the sample scripts in the help files.  After a lot of trial and error, the following codes works very well.  It delays playback on the video for the right amount of time.  The only problem is when the repeat (as it should) the codes runs again.  I want to only run code during the first thru.  Any help would be appreciated.

    Stop();
    var startTime = getTimer ();

    stage.addEventListener (Event.ENTER_FRAME, delay);

    function timeDelay(event:Event):void {}
    var timePassed = getTimer ();
    If ((timePassed-startTime > = 4000) {})
    Play();
    }
    }

    Thank you


    Doug

    Oh, I get it.  Sorry, forgot some of the intricacies of the animation on the timeline.  Yes, as long as your code is on frame 1 and your return your timeline at the frame 1, then the code will load every time.  What you need to do, is have your code on frame 1, then loop back to the frame 2 to start the next iteration of the film.

  • by pushing the tables only once?

    say I have a button that I push to add a term currently selected within a field of field / text entries in a table, but I don't want to accidentally add the same option twice, or see the same option again and again, what should I do for the table?

    Here is the original for a table called aNameslist and a variable called namesD

    addmcD.onPress = function() {}
    aNameslist.push (namesD);
    }

    What is necessary to move from an output like

    Jane Doe, Jane Doe, Calaway give, John Doe, Jim Dutchy, John Doe, Jane Doe

    something like

    Calaway give, John Doe, Jane Doe, Jim Dutchy

    ?

    You can remove duplicates from any array by passing to the function below:

    a = removeDupsF (a);

    function removeDupsF(a:Array):Array {}

    for (var i = a.length - 1; i > = 0; i--) {}

    for (var j = i-1; j > = 0; j-) {}

    {if(a[i]==a[j])}

    a.splice (i, 1);

    break;

    }

    }

    }

    return a;

    }

  • Receptive Slide height develops all the objects on the slide master background.

    Hey,.

    If I build a sensitive project and slides, I need to unlock the height of the slide in mobile mode on some slides to create a scrolling to display more content.

    When I adjust the height of the blade, it develops all the objects in the background of the slide (my header, title...). These elements are not merged.

    Is there anyway that I can adjust the height of the blade so that it is not developing all the objects on the slide, only the backdrop (i.e. the white canvas). I try to use a model of slides for content pages.

    Or is the only way around it to create a number of different slide masters with heights of slide?

    See you soon

    Hello

    I feel your pain. I struggled with this for a long time, but finally found a solution.

    If you want to extend the height of the blade, creating a scroll bar. But you want certain elements to stretch and others do not.


    Object to Extensible NOT / Static

    • Create in the Slide Master
    • Set the properties top and % Relative height.

    Stretch/dynamic objects

    • Create directly in slide film
    • Set the Top % Relative property
    • Set the Height property for % (not related).

    I recommend to create a slide film finalized and then duplicate this slide for all other instances.

    Let me know if it works.

  • IO_ERROR event fires only for first wrong url

    This is my first Flash application, so please bear with me.

    In the example below, I have a number of files I load using Chargers.

    However, when I have more than one url wrong (missing file, bad domain,...) the IO_ERROR event fires only once. For all subsequent bad urls, the system does nothing and hangs just (when loading consecutively).

    One solution is to load all images silmultaneously, but I still want to know what is the problem.

    Thought I'd post the solution here.

    In the end, the problem was: load a file from a non-existent domain not triggered any error.

    It's apparently a problem with FF and OS / X

    http://tinyurl.com/5q87n3

  • VI, who controls the action only when you press the button

    I have two stepper motors that control a cart on each axis.  My goal is to make a program that helps others in my lab to easily assign a direction and the distance they want the cart to move and then run the command.  I want them to be able to update the direction and the distance and then press a GO button which will be sent the signal to the basket.  To do this, use a VISA resource.  I have the MOST done program.  The question that I am running is my button does not work as I want.  It is not always save the push or he sends the signal several times on the drive.  I am attaching the 2 screws that are implementing the mechanics of my button in two ways.  Any help as to what I can to one or the other VI so he could make the order only once while leaving the operator make additional entry changes constantly and the start of the VI.  Thank you.

    You should use the structure of the event so good for you on one of these examples to try to use it.  Tied, is implementation that actually works.  You press once on the button and acts on it once.  Pressing stop or close the window works as well.

    EDIT: If you have some free time you must follow some training and try to find examples on the structure of the event.

    Training center of NOR

    NEITHER start-up

    -Hardware Basics

    -LabVEW databases

    -DAQ Application tutorials

    Introduction to LabVIEW for 3 hours

    Introduction to LabVIEW for 6 hours
    Paced self-study for students
    Self Paced Training beginner to advanced, required SSP
    LabVIEW training Wiki

  • Recognizing the touch of a button only once

    Hello

    Im making a flash project that is connected to a PIR sensor that triggers a keypress to the game SWF. Only problem, is that the sensor maintains trigger the keypress which makes the swf file start over and over again. How I would say actionscript only acknowledge the keypress once and only plays the swf only once?

    Yep - if you remove the listener inside the handler function, then it will get deleted after you press a key. something like this:

    stage.addEventListener (KeyboardEvent, handler);

    function handler(event:KeyboardEvent):void

    {

    stage.removeEventListener (KeyboardEvent, handler);

    launch swf

    }

    (once you remove the listener, has no way to Manager to get called again, and the launch of swf will happen only once)

  • Look at a swf in HTML-user can view only once

    Hello

    I have my swf files which are called in the browser when the user opens the page.

    To ensure that my swf is not used by the user for its other objectives, I got it as a strict view from the HTML page that has a variable. Same variable increased from swf in HTML code.

    If the two variables match only swf then starts preloading. This works very well for the first time.

    But when the user open the same page, second time, is no longer able to view the preloader that does not progress further.

    When I delete my temp file so the user is again able to view the swf only once file.

    Can someone tell me;

    1. What is the reason the swf for the temporary file cannot access variable of its HTML code

    2. I do it wrongly?

    3. do I need to clear the cache every time, or there is another method to do?

    Thank you.

    Hi kglad,.

    I found the solution.

    whenever I used "Play();" action I changed it with "gotoAndPlay();

    I found somewhere on the net that play, stop the actions sometimes fail with IE & I just replaced "play()" with "gotoAndPlay()" it was like a magical thing and my swf works fine under IE now.

    Thank you for your reply & help.

  • Why my MBP retina nine come with only 100 GB against 120 GB as shown. (He says 20 GB has been used, but I just bought the laptop) is enough space of 100 GB. I'm not a gamer or anything like that. Just need the computer for College

    Why my MBP retina nine come with only 100 GB against 120 GB as shown. (He says 20 GB has been used, but I just bought the laptop) is enough space of 100 GB. I'm not a gamer or anything like that. Just need the computer for College

    How to report the storage capacity - Support Apple OS X and iOS

    If you bought the Apple MBP, you have 14 days to swap for a most appropriate mac.

    If bought from a different dealer, you will need to contact them about the Exchange / return policy.

Maybe you are looking for

  • Re: Satellite Pro L550-17R Performance Options at startup - Windows 7 32 bit

    I have a Satellite Pro L550-17R and every time you start the performance Option is displayed using Win 7 32 bitIs someone can please tell me how I prevent this. Thank you.

  • knowledge of the limited definition

    Hello I just discovered the following problem with the IDE: CVI provides a nice feature "Go to definition", surprisingly it seems to not always work... The test scenario: in the call to viFindRsrc (), I tried the following regular expression: "ASRL?

  • A PDF file will not print on premium c309g-m

    I can't get the printer to print a PDF file. No matter what settings I do or what I can do to the printer, it won't print a PDF file. I export PDF files to jpg and print the image. How to make this work? I'm about to throw the printer out the window

  • 7410 all In One intermittent at best

    Using Windows XP Home, Service Pack 3, 3 GHz, 3 GB RAM.  .  I have a 7410 All In One connected via USB.  3 years old. In the last 6 months, it was clear a persistent problem.  When off tension for some time, it will simply stop working. Disconnect -

  • Weird characters added to the URL string.

    So, while I use ColdFusion at work, I also use it on my personal website, where I host a blog and photos in the gallery.Whenever I click on a message or a photo from the Gallery, I noticed that the URL is added with a kind of token.For example, this: