Write a complete getSomeEntry method to add to the ArrayBag
Write a complete getSomeEntry() method to add to the ArrayBag class. ArrayBag implements BagInterface using an array. The method returns an unspecified entry of the ArrayBag. You can decide which entry to return. Be sure to account for all possible times when the method could be invoked. The method header is: public T getSomeEntry() For this question, you are writing code at the implementation level. This means you have access to the private instance data variables: private T[] bag private int numberOfEntries You can assume the following methods are already implemented: public boolean add(T newEntry) public boolean isEmpty() public boolean contains(T anObject) public boolean remove() public boolean remove(T anEntry) public int getFrequencyOf(T anEntry) public int getCurrentSize() public void clear()
Solution
From the question we know that we have an interface name \"BagInterface\" and class \"ArrayBag\" implements the interface using an array.
And another important point is that \"ArrayBag\" is a generic class and \"T\" is a parameter of the class.
Now we have to implement \"getSomeEntry()\" method and will add to the \"ArrayBag\" class.
LETS CODE
public class ArrayBag <T>{ // This is class that implements an interface. T is the parameter of type // interface which is \"BagInterface\".So we will use BagInterface in the form of T
private T[] Bag; // This is the array of interface instances. It will contain all instances of // interface in contiguous block of an array
private int numberOfEntries;
public T getSomeEntry() // Our method starts here
{
private T baginterface_variable; // we define interface variable. This method will return the entry so we will save the array entry in this variable and will return this variable.
if(this.isEmpty()) //we check if array is empty it means we cant return any entry so we simple create an entry using add() method provided to us.
{
for(int i=0;i<5;i++)
{
this.add(new BagInterface{}); // this loop will create 5 blocks of contiguous blocks of memory. Here add() method takes a parameter and that parameter will get added in array.
\"new BagInterface{}\" means we creating instance of anonymous class which refer to our \"BagInterface()\" instance.
}
baginterface_variable=T[0]; //we will save our first array entry.
this.remove(T[0]); // then we will remove the first entry.We removing first entry because everytime methods calls we need to return new entry.
return baginterface_variable; //then we return the baginterface_variable which contains first array entry
}
else{ // if our array is not empty we execute this code
baginterface_variable=T[0]; // again save first entry
this.remove(T[0]); //remove entry
return baginterface_variable; //return the entry
}
}
}
