Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Having trouble on 2nd //TODO comment. public static HashSet<Integer> doHashSetRe

ID: 3925549 • Letter: H

Question

Having trouble on 2nd //TODO comment.

public static HashSet<Integer> doHashSetRemoveFromSmallest(int numItems) {

       System.out.print("doHashSetRemoveFromSmallest: ");
       HashSet<Integer> set = new HashSet<>();

       // TODO Write code that adds integers 0 through (numitems - 1)
       // to set.

       for(int i=0; i<=numItems-1; i++){
           set.add(i);
       }
      
       long startTime = getTimestamp();

       // TODO Write code that removes the smallest element from set,
       // repeatedly until the set is empty.

      
      
       long endTime = getTimestamp();
       long totalTime = endTime - startTime;
       System.out.println(totalTime);
      
       return set;
   }

Explanation / Answer

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package chegg;

import java.util.Collections;
import java.util.HashSet;


public class Program {

  
public static HashSet<Integer> doHashSetRemoveFromSmallest(int numItems) {
System.out.print("doHashSetRemoveFromSmallest: ");
HashSet<Integer> set = new HashSet<>();
// TODO Write code that adds integers 0 through (numitems - 1)
// to set.
for(int i=0; i<=numItems-1; i++){
set.add(i);
}

Integer min;
long startTime = System.currentTimeMillis();
// TODO Write code that removes the smallest element from set,
// repeatedly until the set is empty.
while(!set.isEmpty())
{
min = Collections.min(set);
set.remove(min);
System.out.println("Removing "+min+" from set");
}

long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println(totalTime);

return set;
}

public static void main(String[] args)
{
HashSet<Integer> s;

s = doHashSetRemoveFromSmallest(5);
  
//Should be zero since we will be removing all the min elements till the size of set become zero
System.out.println("Size of set is : "+s.size());
}
}

run:
doHashSetRemoveFromSmallest: Removing 0 from set
Removing 1 from set
Removing 2 from set
Removing 3 from set
Removing 4 from set
4
Size of set is : 0
BUILD SUCCESSFUL (total time: 1 second)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote