Home > Back-end >  My java assignment asks us to create a method that, when called, will fill a hashtable with 20 rando
My java assignment asks us to create a method that, when called, will fill a hashtable with 20 rando

Time:02-03

This method almost works but it randomly skips over some numbers and never gets all 20 numbers.

    public static void callHashTable()
    {
        Random rand = new Random();
        ArrayList<Integer> aList = new ArrayList<Integer>();
        Hashtable<Integer, String> hTable = new Hashtable<Integer, String>();
        System.out.println("\nNow Populating Hashtable:...");
        for( int i =0; i < 20; i  )         
        {
            aList.add(i);
        }
        
        for( int i = 0; i < 20; i  )
        {
            int index = rand.nextInt(aList.size());
            String str = String.valueOf(index);
            hTable.put(index, str);
            aList.remove(index);        
        }
            
        System.out.println("Hash Table Size: "   hTable.size());
        System.out.println(hTable);
        return;
    }

Output Now Populating Hashtable:... Hash Table Size: 9 {18=18, 10=10, 7=7, 6=6, 5=5, 4=4, 3=3, 1=1, 0=0}

CodePudding user response:

Your problem is this piece of code:

for( int i = 0; i < 20; i  )
    {
        int index = rand.nextInt(aList.size());
        String str = String.valueOf(index);
        hTable.put(index, str);
        aList.remove(index);
    }

During the iteration list shrinks and indexes get repeated. Whilst that's happening values for the keys that are already present in the map are being replaced. Hence you'll never get 20 entries in the map that way.

But if you make use of list values instead of indexes you'll avoid repetitions of keys:

        for ( int i = 0; i < 20; i  ) {
            int index = rand.nextInt(aList.size());
            String str = String.valueOf(index);
            hTable.put(aList.remove(index), str);
        }

Also, note:

  • Hashtable is a legacy class, which is not encouraged to be used. Substitute it with an implementation of the Map interface ( HashMap is a general-purpose implementation that is almost identical to Hashtable but it's more efficient because its methods aren't synchronized).
  • write your code against interfaces List, Map, not against implementations.

CodePudding user response:

When this runs: String str = String.valueOf(index); hTable.put(index, str);

you're putting the index value into your hash table, not the value that the index is supposed to represent in aList.

I think you want to actually pull a value from aList using the index, aList isn't actually getting accessed with your current code.

  •  Tags:  
  • Related