Create a generic class, madLabClass • The class will have 2 fields o One is an i
ID: 3849004 • Letter: C
Question
Create a generic class, madLabClass •
The class will have 2 fields
o One is an integer for an index
o The second is an array of the generic class type
• A constructor for the class will take in one parameter of int
o This will create the array backing field to be of the size sent in
o The index will be set to 0
• A function called GetValue
o will print out the current value of the array being pointed at by the index
o will advance the index by one
o if the index is out of range, loop it back to the beginning
Explanation / Answer
/**
* madLabClass class defintion
* of generic type
* */
//madLabClass.java
public class madLabClass<T>
{
//private data members
private int index;
private Object[] object;
//constructor that takes size as integer value
public madLabClass(int size)
{
//set index=0
index=0;
//create an array of object of type generic
object=new Object[size];
}
//helper method to set value
public void Setvalue(T val)
{
if(index<0 || index>object.length)
throw new IndexOutOfBoundsException();
else
{
object[index]=val;
index++;
}
}
//GetValue method
public void GetValue()
{
//print the value at index
System.out.println(object[index-1]);
//decrement the index by 1
index--;
/*loop back to index=0 if the current index is
out of the length of the object */
if(index<0)
index=0;
}
}//end of the class madLabClass
-------------------------------------------------------------
/**
* Sample java proram to test madLabClass class
* */
//DriverProgram.java
public class DriverProgram
{
public static void main(String[] args)
{
//create an instance of the madLabClass class of type string
madLabClass<String> workingDays=new madLabClass<>(5);
//add strings values to workingDays object
workingDays.Setvalue("monday");
workingDays.Setvalue("tuesday");
workingDays.Setvalue("wednesday");
workingDays.Setvalue("thursday");
workingDays.Setvalue("friday");
//print values in the workingDays object
//calling GetValue method
workingDays.GetValue();
workingDays.GetValue();
}
}
-------------------------------------------------------------
Sample output:
friday
thursday
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.