Please help, how to implement hasNext() and next() of a HashSet iterator?

Hi guys,
Can someone help me out with this? I'm struggling to write an iterator (the hasNext() and next() methods) for a SimpleHashSet class and I keep failing. I have a basic unit test, which goes like this:
@Test
    public void testIterator() {
        SimpleHashSet<String> instance = new SimpleHashSet<String>();
        assertTrue(instance.iterator() != null);
        Iterator<String> it = instance.iterator();
        assertFalse(it.hasNext()); //Should return false on an empty HashSet
        assertTrue(it.next() == null); //Should return null on an empty HashSet
        instance.add("First");
        instance.add("Second");
        assertTrue(it.hasNext()); // Return true if has first element
        assertTrue(it.next() != null); //Should return first element
        assertTrue(it.hasNext()); //Return true if has second element
        assertTrue(it.next() != null); //Should return second element
        assertFalse(it.hasNext()); //Return false, no third element
        assertTrue(it.next() == null); //Return true, no third element         
    }and I can't figure out a way to pass all of these tests. I have written several variants and none of them works completely, only partially, inconsistently. I just don't know how to write it.
The SimpleHashSet is declared like this:
public class SimpleHashSet<E> extends AbstractSet<E> {
    private static final int SIZE = 11;
    LinkedList<E>[] buckets = new LinkedList[SIZE];
}I appreciate all help and guidance,
PR.

Awesome, great answers, very helpful, thanks very much. Careful debugging and testing led me to a working solution. It passes my tests. This is what I have:
    @Override
    public Iterator<E> iterator() {
        final SimpleHashSet<E> here = this;
        Iterator<E> it = new Iterator<E>() {
            private final SimpleHashSet<E> mySet = here;
            private List<LinkedList<E>> bucketList = Arrays.asList(mySet.buckets);
            private Iterator<LinkedList<E>> bucketsIterator = bucketList.iterator();
            private LinkedList<E> currentBucket;
            private Iterator<E> elements;
                currentBucket = bucketsIterator.next();
                elements = currentBucket.iterator();  
            @Override
            public boolean hasNext() {
                while (bucketsIterator.hasNext()) {
                    if (elements.hasNext()) {
                        return true;
                    } else {
                        currentBucket = bucketsIterator.next();
                        elements = currentBucket.iterator();
                if (elements.hasNext())
                    return true;
                return false;
            @Override
            public E next() {
                while (bucketsIterator.hasNext()) {
                    if (elements.hasNext()) {
                          return elements.next();
                    } else {
                        currentBucket = bucketsIterator.next();
                        elements = currentBucket.iterator();
                if (elements.hasNext())
                    return elements.next();
                if (!bucketsIterator.hasNext())
                    throw new NoSuchElementException();
                return null;
        return it;
    }I'm only not sure if it behaves the same as an original HashSet iterator. I doubt. The problem with my implementation is that both hasNext() and next() progress the internal iterators forward, so i.e. calling hasNext() on an empty set will progress the internal iterators to the end, so then adding some elements and calling hasNext() again will return false. I couldn't figure out a way that hasNext() does not progress the iterators, so that only next does that. Both hasNext() and next() are dependent on each other in my example. But it works.
Thanks,
PR.

Similar Messages

  • Hi, when ever I'm using 3G, on my Iphone4 sim stops working and Network is lost, this started after I updated my phone with  6.0.1(10A523)version. Please help how to solve this problem.

    Hi, when ever I'm using 3G, on my Iphone4 sim stops working and network is lost, this started after I updated my phone with  6.0.1(10A523)version. Please help how to solve this problem. Thanks.

    Photos/videos in the Camera Roll are not synced. Photos/videos in the Camera Roll are not touched with the iTunes sync process. Photos/videos in the Camera Roll can be imported by your computer which is not handled by iTunes. Most importing software includes an option to delete the photos/videos from the Camera Roll after the import process is complete. If is my understanding that some Windows import software supports importing photos from the Camera Roll, but not videos. Regardless, the import software should not delete the photos/videos from the Camera Roll unless you set the app to do so.
    Photos/videos in the Camera Roll are included with your iPhone's backup. If you synced your iPhone with iTunes before the videos on the Camera Roll went missing and you haven't synced your iPhone with iTunes since they went missing, you can try restoring the iPhone with iTunes from the iPhone's backup. Don't sync the iPhone with iTunes again and decline the prompt to update the iPhone's backup after selecting Restore.

  • After updating my Macbook Pro retina display to os x yosemite 10.10.2, the mause and track pad locks, and do not respond especially when using the Mac for a long period, please help, how can I solve this, I do not like feel like in windows, so I paid

    after updating my Macbook Pro retina display to os x yosemite 10.10.2, the mause and track pad locks, and do not respond especially when using the Mac for a long period, please help, how can I solve this, I do not like feel like in windows, so I paid good money for this mack, I feel calm

    Hi Buterem,
    I'm sorry to hear you are having issues with your MacBook Pro since your recent Yosemite update. I also apologize, I'm a bit unclear on the exact nature of the issue you are describing. If you are having intermittent but persistent responsiveness issues with your mouse or trackpad, you may want to try using Activity Monitor to see if these incidents correspond to occupied system resources, especially system memory or CPU. You may find the following article helpful:
    How to use Activity Monitor - Apple Support
    If the entire system hangs or locks up (for example, if the system clock freezes and stops counting up), you may also be experiencing some variety of Kernel Panic. If that is the case, you may also find this article useful:
    OS X: When your computer spontaneously restarts or displays "Your computer restarted because of a problem." - Apple Support
    Regards,
    - Brenden

  • HT201270 i have just updated my old 3GS and now when i am on restore the window is comming up and asking for a password. i have not set up a password for restore, please help how i can restore my date???

    i have just updated my old 3GS and now when i am on restore the window is comming up and asking for a password. i have not set up a password for restore, please help how i can restore my date???

    capriz wrote:
    i have just updated my old 3GS ...
    To what... iOS 7 is Not supported on the 3 GS

  • Blank screen in itunes store-please help im not very technical and when i click on my itunes app the screen is blank how can i fix this please?

    Blank screen in itunes store-please help im not very technical and when i click on my itunes app the screen is blank how can i fix this please?

    See if any of the following fix it.
    Try logging out of your account on your phone by tapping on your id in Settings > iTunes & App Store and tap 'Sign Out' on the popup and then log back in.
    If that doesn't fix it then try closing the iTunes store app via the phone's multitasking bar and see if it works properly when you open the app : double-click the home button to open the taskbar and then swipe or drag iTunes from there up and off the top of the screen to close it, and the click the home button to close the taskbar.
    A third thing to try is a soft-reset : press and hold both the sleep and home buttons for about 10 to 15 seconds (ignore the red slider), after which the Apple logo should appear - you won't lose any content, it's the equivalent of a reboot.

  • I bought a used iphone from a friend and I am not able to use it in Ethiopia. It is carrier blocked. Can you please help how could I unlock my iphone 4?.

    I bought a used iphone from a friend and I am not able to use it in Ethiopia. It is carrier blocked. Can you please help how could I unlock my iphone 4?.

    Unlikely as you do not meet there requirements for unlocking.
    Have your friend the provided the phone contact them.  Based on your statements I am concluding he was or still is an AT&T customer, that is one of the requirements of getting the device unlocked.

  • Please help! I have photoshop and iphoto does not show it in my preferences edit window. How do I get it as an option in my preferences.

    Please help! I have photoshop and iphoto does not show it in my preferences edit window. How do I get it as an option in my preferences.

    I tried it and nothing changed. Even when I right click on an indiviual image all it does is duplicate it. Iphoto seems to be recognizing my external hard drive as an editor......cannot get photoshop except to drag a picture into photoshop from iphoto, and once I have worked on it and saved it to iphoto I cant find it anywhere.

  • I have windows 8 and I got this error "Adobe Photoshop has stopped working" whenever I start a program. please help. how can I fix this problem? many thanks

    i have windows 8 and I got this error "Adobe Photoshop has stopped working" whenever I start a program. please help. how can I fix this problem? many thanks

    Please read these and proceed accordingly:
    http://blogs.adobe.com/crawlspace/2012/07/photoshop-basic-troubleshooting-steps-to-fix-mos t-issues.html
    http://forums.adobe.com/docs/DOC-2325

  • I can't cancel my creative cloud membership.Links and phone number don't work. PLEASE HELP, I WILL NOT PAY THE NEXT INVOICE!!!

    I can't cancel my creative cloud membership.Links and phone number don't work. PLEASE HELP, I WILL NOT PAY THE NEXT INVOICE!!!

    This is an open forum, not Adobe support... You need Adobe support to cancel a subscription
    -start here https://forums.adobe.com/thread/1703848
    -or by telephone http://helpx.adobe.com/x-productkb/global/phone-support-orders.html
    --and two links which may provide more details, if the above links don't help you
    -http://helpx.adobe.com/x-productkb/policy-pricing/return-cancel-or-change-order.html
    -http://helpx.adobe.com/x-productkb/policy-pricing/cancel-membership-subscription.html

  • Please help how to save a movieclip in flash to svg...and how to retrive the saved svg to movieclip in flash?

    hi all
    please help how to save a movieclip in flash to svg...and how
    to retrive the saved svg to movieclip in flash?
    thanks

    Do you mean from flash in a web page or do you mean
    converting the swf file format (maybe with a decompiler or
    whatever).
    If you're meaning to do it from flash in a web page:
    You can't save a movieclip from flash to svg. You could
    perhaps record drawingAPI commands and create the appropriate svg
    output in an internal xml object which you then send to the server.
    But I don't know of any pre-built classes to do that (disclaimer:
    because I don't know of any doesn't mean they don't exist).
    Going from svg to flash is doing it the other way around.
    Converting the svg paths back to actionscript drawing commands. I
    think I've seen some examples of this online somewhere.

  • My ipod keeps asking me to restore and when i do restore it just restarts and asks me to connect to itunes and starts again.please help its my sons bday and this is his present

    my ipod keeps asking me to restore and when i do restore it just restarts and asks me to connect to itunes and starts again.please help its my sons bday and this is his present

    Maybe:
    Restore loop (being prompted to restore again after a restore successfully completes)
    Troubleshoot your USB connection. If the issue persists, out-of-date or incorrectly configured third-party security software may be causing this issue. Please follow Troubleshooting security software issues. .
    Next try placing in DFU mode and then restoring.
    How to put iPod touch / iPhone into DFU mode « Karthik's scribblings
    Then try restoring on another computer.
    Last, make an appointment at the Genius Bar of an Apple store.
    Apple Retail Store - Genius Bar

  • I just bought a new iPhone and accidentally backed it up with my old iPhone backup, I do not want this. I lost everything on my new phone and I need it back. PLEASE HELP! This includes pictures and texts, etc.

    I just bought a new iPhone and accidentally backed it up with my old iPhone backup, I do not want this. I lost everything on my new phone and I need it back. PLEASE HELP! This includes pictures and texts, etc.

    So just to be clear, when you say "just bought" how long ago was that? Is it on this new iPhone that you had pictures, texts, etc that you want? Were you backing up to iCloud or onto iTunes?
    This may not help for everything but if you go to iCloud.com and log in, are you able to find your pictures there?

  • Please Help,how do i get my iphone 4 to play all my songs from icloud, it is currently only playing just a smal number of songs from my library which is stored in icloud.

    Please Help,how do i get my iphone 4 to play all my songs from icloud, it is currently only playing just a smal number of songs from my library which is stored in icloud.

    There are a number of OS X apps, many free, that will save your messages, allowing to view and print them. 
    http://www.softwarebbs.com/wiki/How_to_transfer_SMS_from_iPhone_to_Mac,_backup_i Phone_SMS_message_on_Mac
    Google, for other options
    Your "other" of 6 GB may include corrupted data or file sytem errors. If after removing the messages there is still >2GB, you will need to restore the phone in iTunes, first using a backup (made after deleting the messages) and if needed as a new iPhone.
    iTunes: Restoring iOS software

  • How to implement classes and methods in badi's ?

    how to implement classes and methods in badi's? and where i have to write the code based on the requirement?can anyone explain me briefly?

    Hi
    Every BADI by default Implements an INTERFACE which already contains some methods with parameters.
    So you have to find the relavenet method based on the related paramters (by checking the fields in that paramters) you have to double click on the method and to write the code.
    see the doc
    DEFINING THE BADI
    1) execute Tcode SE18.
    2) Specify a definition Name : ZBADI_SPFLI
    3) Press create
    4) Choose the attribute tab. Specify short desc for badi.. and specify the type :
    multiple use.
    5) Choose the interface tab
    6) Specify interface name: ZIF_EX_BADI_SPFLI and save.
    7) Dbl clk on interface name to start class builder . specify a method name (name,
    level, desc).
    Method level desc
    Linese;ection instance methos some desc
    8) place the cursor on the method name desc its parameters to define the interface.
    Parameter type refe field desc
    I_carrid import spfli-carrid some
    I_connid import spefi-connid some
    9) save , check and activate…adapter class proposed by system is
    ZCL_IM_IM_LINESEL is genereated.
    IMPLEMENTATION OF BADI DEFINITION
    1) EXECUTE tcode se18.choose menuitem create from the implementation menubar.
    2) Specify aname for implementation ZIM_LINESEL
    3) Specify short desc.
    4) Choose interface tab. System proposes a name fo the implementation class.
    ZCL_IM_IMLINESEL which is already generarted.
    5) Specify short desc for method
    6) Dbl clk on method to insert code..(check the code in “AAA”).
    7) Save , check and activate the code.
    Some useful URL
    http://www.esnips.com/doc/e06e4171-29df-462f-b857-54fac19a9d8e/ppt-on-badis.ppt
    http://www.esnips.com/doc/10016c34-55a7-4b13-8f5f-bf720422d265/BADIs.pdf
    http://www.esnips.com/doc/43a58f51-5d92-4213-913a-de05e9faac0d/Business-Addin.doc
    http://www.esnips.com/doc/1e10392e-64d8-4181-b2a5-5f04d8f87839/badi.doc
    www.sapgenie.com/publications/saptips/022006%20-%20Zaidi%20BADI.pdf
    http://www.sapdevelopment.co.uk/enhance/enhance_badi.htm
    http://help.sap.com/saphelp_nw04/helpdata/en/04/f3683c05ea4464e10000000a114084/content.htm
    http://help.sap.com/saphelp_nw04/helpdata/en/e6/d54d3c596f0b26e10000000a11402f/content.htm
    http://help.sap.com/saphelp_nw2004s/helpdata/en/c2/eab541c5b63031e10000000a155106/frameset.htm
    Now write a sample program to use this badi method..
    Look for “BBB” sample program.
    “AAA”
    data : wa_flights type sflight,
    it_flights type table of sflight.
    format color col_heading.
    write:/ 'Flight info of:', i_carrid, i_connid.
    format color col_normal.
    select * from sflight
    into corresponding fields of table it_flights
    where carrid = i_carrid
    and connid = i_connid.
    loop at it_flights into wa_flights.
    write:/ wa_flights-fldate,
    wa_flights-planetype,
    wa_flights-price currency wa_flights-currency,
    wa_flights-seatsmax,
    wa_flights-seatsocc.
    endloop.
    “BBB”
    *& Report ZBADI_TEST *
    REPORT ZBADI_TEST .
    tables: spfli.
    data: wa_spfli type spfli,
    it_spfli type table of spfli with key carrid connid.
    *Initialise the object of the interface.
    data: exit_ref type ref to ZCL_IM_IM_LINESEL,
    exit_ref1 type ref to ZIF_EX_BADISPFLI1.
    selection-screen begin of block b1.
    select-options: s_carr for spfli-carrid.
    selection-screen end of block b1.
    start-of-selection.
    select * from spfli into corresponding fields of table it_spfli
    where carrid in s_carr.
    end-of-selection.
    loop at it_spfli into wa_spfli.
    write:/ wa_spfli-carrid,
    wa_spfli-connid,
    wa_spfli-cityfrom,
    wa_spfli-deptime,
    wa_spfli-arrtime.
    hide: wa_spfli-carrid, wa_spfli-connid.
    endloop.
    at line-selection.
    check not wa_spfli-carrid is initial.
    create object exit_ref.
    exit_ref1 = exit_ref.
    call method exit_ref1->lineselection
    EXPORTING
    i_carrid = wa_spfli-carrid
    i_connid = wa_spfli-connid.
    clear wa_spfli.
    Reward points for useful Answers
    Regards
    Anji
    Message was edited by:
            Anji Reddy Vangala

  • I want to cahage my peyment method ( i wana do take out my credit card  from there) please help how???

    want to cahage my peyment method ( i wana do take out my credit card  from there) please help how???

    You can't change to 'None' until you clear up the previous payment problem.  Add a fresh iTunes gift card, or add a credit card, and then once the billing issue clears, you can choose 'None' again.

Maybe you are looking for

  • Invoice of downpayment of 100%

    Sometimes  when we sell  a material we sometimes ask the downpayment of 100% of the order. When we deliver a material we issue a delivery note and the final invoice,  but it is impossible to issue a final invoice of 0 Euro with a registration on the

  • RCVR_DETERMINATION" NO_RECEIVER_CASE_ASYNC  error while monitering

    hi every body.... <?xml version="1.0" encoding="UTF-8" standalone="yes" ?> - <!--  Receiver Identification   --> - <SAP:Error xmlns:SAP="http://sap.com/xi/XI/Message/30" xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/" SOAP:mustUnderstand="">  

  • SRM 7 - central contract different webdynpro screen

    Hello, I'm on an SRM 7 SP05 system. When i open a central contract via the strategic purchasing -> contract management -> POWL (click on number) the document is shown in light blue the loading bar and screen colors are different from all the other sc

  • I receive messages only when I reset my N82

    Hi, I've been using my N82 past 2 years. Sometime back I started getting this problem - If someone sent me a text, I received it only if I reset my phone. I proceeded to upgrade the firmware. Thought that might help. Currently, it is V 35.0.002 for N

  • ROWID in update statment

    Hi all, Please advice if following statment will update correct rows?: for x in (select rowid from table where col=345 and col2=567 and col3=678) loop update table set col6=344 wher rowid=x.rowid; end loop; I just whant to be sure that refference to