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

Create a class called GiftExchange that simulates drawing a gift at random out o

ID: 3718731 • Letter: C

Question


Create a class called GiftExchange that simulates drawing a gift at random out of a box.
The class is a generic class with a parameter of type T that represents a gift and where T can be a type of any class. The class must include the following
1. An ArrayList instance variable that holds all the gifts,The ArrayList is referred to as theBox.
2. A default constructors that creates the box.
3. An add method that adds a gift to the box.
4. A drawGift method that
1. Ensure the box is not empty, if it is empty returns null.
2. If not empty
1. Selects a gift at random from the Box.
2. Removes that gift from the BoX
3. Returns the selected gift.
5. You may add any other method(s) you think you need however no additional functionality ls required.
6. No Javadoc or import statements required.

Explanation / Answer

CODING:

import java.util.ArrayList;

import java.util.Random;

public class GiftExchange<T> {

  

   private ArrayList<T> giftList;

  

   public GiftExchange() {

       giftList = new ArrayList<>();

   }

  

   void addGift(T gift){

       giftList.add(gift);

   }

  

   public T drawGift(){

       int n = giftList.size();

       if(n == 0)

           return null;

       else{

           Random rand = new Random();

           int randIndex = rand.nextInt(n);// 0 to n-1

           T gift = giftList.get(randIndex);

           giftList.remove(randIndex);

           return gift;

       }

   }

}

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