Create a class called GiftExchange that simulates drawing a gift at random out o
ID: 3833513 • 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 :
- An ArrayList instance variable that holds all the gifts,The ArrayList is referred to as the box.
- A default constructors that creates the box.
- An add method that adds a gift to the box.
- A drawGift method that Ensure the box is not empty, if it is empty returns null. If not empty Selects a gift at random from the Box. Removes that gift from the Box Returns the selected gift.
No Javadoc or import statements required.
Explanation / Answer
Please find my implementation.
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;
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.