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

Write a generic class names Undo Variable. It should act like a variable with an

ID: 3834263 • Letter: W

Question

Write a generic class names Undo Variable. It should act like a variable with an undo feature. There should be 3 methods. The set method sets the value of the variable. The get method gets the value of the variable. The undo method changes the value to the previous value. After a sequence of five set calls and four undo calls, the get method should return the value assigned by the first set call. Details of initialization and error handling are up to you. An ArrayList might be useful for implementing this class along with the following methods of ArrayList

Explanation / Answer

import java.util.ArrayList;

public class UndoVariable<T>
{
   ArrayList<T> list=new ArrayList<T>();
   T value=null;
  
   public void setValue(T val)
   {
       value=val;
       list.add(value);
      
   }
  
   public T getValue()
   {
       return value;
   }
  
   public void undoValue()
   {
  
       if(list.size()!=1)
       {
       list.remove(list.size()-1);
       value=list.remove(list.size()-1);
       }
      
       else
       {
           throw new IllegalArgumentException("invalid undo");
       }
   }
  
}

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