Question

In: Computer Science

Using the implementation of the array based list given, write a CLIENT method (that is NOT...

Using the implementation of the array based list given, write a CLIENT method (that is NOT part of the class) called replace, that given a value and a position replaces the value of the element at that position. REMEMBER error checking

public static void replace( List aList, int newValue, int position)

public class ArraybasedList implements MyListInterface{
  private static final int DEFAULTSIZE = 25;
  
// Data members:
  private int currentSize;
  private int maxSize;
  private S[] elements;

  //default constructor has NO parameters
  public ArraybasedList(){
    this.currentSize =0;
    this.maxSize = DEFAULTSIZE;
    this.elements = (S[]) new Object[maxSize];
  }
  
  // non-default constructor
  public ArraybasedList(int maxElements) {
    if (maxElements <= 0)
      throw new ListException("The size of the list must be > zero.");
    
    this.currentSize =0;  // set the current size to zero
    this.maxSize = maxElements; // store the size in maxSize

// allocate storage for elements
    this.elements = (S[] ) new Object[this.maxSize];  

 }

  // begin implementing methods
  /**
*  This method returns true if the current
*  size of the list is zero.
*
*  
*
*/
  public boolean isEmpty() {
   return ( this.currentSize == 0); 
  }
  
  /**
*  This method returns true if the current
*  size of the list equals the maximum size 
*  of the list.
*
* 
*
*/
  public boolean isFull(){
    return ( this.currentSize == this.maxSize);
  }
  
  
/**
*  This method returns the maximum number
*  of elements the list can hold.
*
*  
*
*/   
  public int getMaxSize(){
    return this.maxSize;
  }

/**
*  This method returns the current number
*  of elements in the list.
*
*  
*
*/   
  public int size(){
    return this.currentSize;
  }
 
  /**
*  This method inserts the value at the given position.
*
*  
*  @param   position location where new value is to be inserted, 0<=position<=current size
*  @param   value new value to be added to the list
*
*/   
  public void add( int position, S value){
//� If the list is full EROR
//� if the position given is < 0 OR > current size, ERROR
//� If position given equals current size, add new element to the end
//� Otherwise, shift all elements whose position is equal to or greater than the given logical position, forward (up) on position in the list and add the new value
  if (this.isFull())
    throw new ListException("Invalid operation, can't add to a full list");
  
  if (position < 0 || position > this.currentSize)
    throw new ListException("Invalid operation, position must be between 0 and " + this.currentSize);
  
  if (position == this.currentSize)
    this.elements[currentSize] = value;
  else{
    for( int i= this.currentSize-1;  i >= position;  i--)
      this.elements[i+1] = this.elements[i];
    
    this.elements[position] = value;
  }
  this.currentSize++;
  }// end add at position
  
  /**
*  This method adds a new value to the end of a list.
*
* 
*  @param   value new value to be added to the list
*
*/   
   public void add( S value){
  this.add( this.currentSize, value);
}// add at end

   public S remove(int position) {
// Precondition:  The is list not empty.
// Precondition:  0<= position <= current size-1 of list
 S tempValue;
 
  if ( this.isEmpty() || position > currentSize-1 || position < 0 )
   throw new ListException("This delete can not be performed "
    + "an element at position " + position 
    + " does not exist " );


//1. Remove the desired value, and shift elements

// Store the value in the list to be deleted
// NOTE:  it must be cast to type S   
 tempValue = (S)this.elements[position];
 
// Shift existing elements down one position
// The logical position, is translated to the physical location of
// position -1
  for( int i = position;  i < this.currentSize-1;  i++)
    this.elements[i] = this.elements[i+1];
//2. Decrement the element count.
// Reinitialize the �old� end element to null, and decrement element count
  this.elements[currentSize-1] = null;
  currentSize--;
  return tempValue;
  } // end remove
/**
 * This method removes all occurrences of elements in the list argument from the list object
 * 
 * 
 * 
 * 
 * */
   public boolean removeAll(MyListInterface list){
   // iterate through the list parameter removing each occurrence of 
   // the values it contains
     boolean result=false;

   return result;
   }  
/**
*  This method returns the value at a specific
*  position in the list.  
*
* 
*  @param   position: location of element to return 0<=position

List interface:

public interface MyListInterface<S>{

/**
*  This method returns true if the current
*  size of the list is zero.
*
*  
*
*/
  public boolean isEmpty();
   
/**
*  This method returns true if the current
*  size of the list equals the maximum size 
*  of the list.
*
*  
*
*/
  public boolean isFull();

/**
*  This method returns the maximum number
*  of elements the list can hold.
*
* 
*
*/   
   public int getMaxSize();

/**
*  This method returns the current number
*  of elements in the list.
*
*  
*
*/   
   public int size();

/**
*  This method searches the list for the
*  specified value and returns the index
*  number of the first element containing
*  the value or -1 if the value is
*  not found.
*
*  
*  @param   value:  the search value
*  @return  index of element containing value or -1
*
*/   
  public int find( S value);

/**
*  This method returns the value at a specific
*  position in the list.  
*
*  
*  @param   position: location of element to return 0<=position<current size
*
*/   
   public S get( int position);

/**
*  This method inserts the value at the given position.
*
*  
*  @param   position location where new value is to be inserted, 0<=position<=current size
*  @param   value new value to be added to the list
*
*/   
   public void add( int position, S value);

/**
*  This method adds a new value to the end of a list.
*
*  
*  @param   value new value to be added to the list
*
*/   
   public void add( S value);
   
   
/**
 * This method removes all occurrences of elements in the list argument from the list
 * 
 * 
 * 
 * 
 * */
   public boolean removeAll(MyListInterface<? extends S> list);
 
   /**
 * This method removes and returns the value at position.  0<= position < currentSize
 * 
 * 
 * 
 * 
 * */
   public S remove(int position);
   
/**
*  This method deletes all of the list's contents.
*
*  
*
*/  
  public void clear();
 
/**
*  This method display the contents of the list
*
*  
*
*/
   public String toString();
}

Solutions

Expert Solution

Solution==> Please do comment in case of any query.

Output:-

Required Method:-

   public static void replace( ArraybasedList aList, int newValue, int position) {
      
               //First we need to remove the element at the given location
               aList.remove(position);
       //Now we add the new element at that location
               aList.add(position, newValue);
          
      
   }

Please make sure to read all the comments in main method. I have also implemented get method in ArraybasedList Class.

Code:-

interface MyListInterface<S>{

/**
* This method returns true if the current
* size of the list is zero.
*
*
*
*/
public boolean isEmpty();

/**
* This method returns true if the current
* size of the list equals the maximum size
* of the list.
*
*
*
*/
public boolean isFull();

/**
* This method returns the maximum number
* of elements the list can hold.
*
*
*
*/   
public int getMaxSize();

/**
* This method returns the current number
* of elements in the list.
*
*
*
*/   
public int size();

/**
* This method searches the list for the
* specified value and returns the index
* number of the first element containing
* the value or -1 if the value is
* not found.
*
*
* @param value: the search value
* @return index of element containing value or -1
*
*/   
public int find( S value);

/**
* This method returns the value at a specific
* position in the list.
*
*
* @param position: location of element to return 0<=position<current size
*
*/   
public S get( int position);

/**
* This method inserts the value at the given position.
*
*
* @param position location where new value is to be inserted, 0<=position<=current size
* @param value new value to be added to the list
*
*/   
public void add( int position, S value);

/**
* This method adds a new value to the end of a list.
*
*
* @param value new value to be added to the list
*
*/   
public void add( S value);


/**
* This method removes all occurrences of elements in the list argument from the list
*
*
*
*
* */
public boolean removeAll(MyListInterface<? extends S> list);

/**
* This method removes and returns the value at position. 0<= position < currentSize
*
*
*
*
* */
public S remove(int position);

/**
* This method deletes all of the list's contents.
*
*
*
*/
public void clear();

/**
* This method display the contents of the list
*
*
*
*/
public String toString();
}


class ArraybasedList<S> implements MyListInterface{

   private static final int DEFAULTSIZE = 25;
  
   // Data members:
   private int currentSize;
   private int maxSize;
   private S[] elements;

   //default constructor has NO parameters
   public ArraybasedList(){
   this.currentSize =0;
   this.maxSize = DEFAULTSIZE;
   this.elements = (S[]) new Object[maxSize];
   }
  
   // non-default constructor
   public ArraybasedList(int maxElements) throws Exception {
   if (maxElements <= 0)
   throw new Exception("The size of the list must be > zero.");
  
   this.currentSize =0; // set the current size to zero
   this.maxSize = maxElements; // store the size in maxSize

   // allocate storage for elements
   this.elements = (S[] ) new Object[this.maxSize];

   }
  
   @Override
   public boolean isEmpty() {
       // TODO Auto-generated method stub
       return ( this.currentSize == 0);
  
   }

   @Override
   public boolean isFull() {
       return ( this.currentSize == this.maxSize);
   }

   @Override
   public int getMaxSize() {
       // TODO Auto-generated method stub
       return this.maxSize;
   }

   @Override
   public int size() {
       // TODO Auto-generated method stub
       return this.currentSize;
   }

   @Override
   public int find(Object value) {
       // TODO Auto-generated method stub
       return 0;
   }

   @Override
   public Object get(int position) {
       // TODO Auto-generated method stub
       return this.elements[position];
   }

   @Override
   public void add(int position, Object value) {
       //
       if (this.isFull())
           try {
               throw new Exception("Invalid operation, can't add to a full list");
           } catch (Exception e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }
      
       if (position < 0 || position > this.currentSize)
           try {
               throw new Exception("Invalid operation, position must be between 0 and " + this.currentSize);
           } catch (Exception e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }
      
       if (position == this.currentSize)
       this.elements[currentSize] = (S)value;
       else{
       for( int i= this.currentSize-1; i >= position; i--)
       this.elements[i+1] = this.elements[i];
      
       this.elements[position] = (S)value;
       }
       this.currentSize++;
   }

   @Override
   public void add(Object value) {
       // TODO Auto-generated method stub
       this.add( this.currentSize, (S)value);
   }

   @Override
   public boolean removeAll(MyListInterface list) {
       // TODO Auto-generated method stub
   boolean result=false;

   return result;
   }

   @Override
   public Object remove(int position) {
       // TODO Auto-generated method stub
       S tempValue;
         
       if ( this.isEmpty() || position > currentSize-1 || position < 0 )
           try {
               throw new Exception("This delete can not be performed "
               + "an element at position " + position
               + " does not exist " );
           } catch (Exception e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }


       //1. Remove the desired value, and shift elements

       // Store the value in the list to be deleted
       // NOTE: it must be cast to type S   
       tempValue = (S)this.elements[position];
         
       // Shift existing elements down one position
       // The logical position, is translated to the physical location of
       // position -1
       for( int i = position; i < this.currentSize-1; i++)
       this.elements[i] = this.elements[i+1];
       //2. Decrement the element count.
       // Reinitialize the �old� end element to null, and decrement element count
       this.elements[currentSize-1] = null;
       currentSize--;
       return tempValue;

      
   }

   @Override
   public void clear() {
       // TODO Auto-generated method stub
      
   }
  
}


public class Main {
  
   public static void replace( ArraybasedList aList, int newValue, int position) {
      
               //First we need to remove the element at the given location
               aList.remove(position);
       //Now we add the new element at that location
               aList.add(position, newValue);
          
      
   }
  
   public static void main(String[] args) {
       // Lets create the ArrayBasedLoist
       ArraybasedList<Integer> al = new ArraybasedList<Integer>();
       //Add element in the list
       al.add(5);
       al.add(7);
       al.add(10);
       //Display all the elements of the list
       System.out.println("Our Original ArrayList");
       for(int i=0;i<al.size();i++) {
           System.out.print(al.get(i)+" ");
       }
      
       System.out.println();
       System.out.println("Replace the value at position 2 by 27");
       System.out.println("List After Modification");
       replace(al,27,2);
       //Display the element after Modification
       for(int i=0;i<al.size();i++) {
           System.out.print(al.get(i)+" ");
       }
       System.out.println();
       System.out.println("Replace the value at position 1 by 50");
       System.out.println("List After Modification");
       replace(al,50,1);
       for(int i=0;i<al.size();i++) {
           System.out.print(al.get(i)+" ");
       }

   }

}

Hope you will like the answer.

Thanks.


Related Solutions

Write an array-based implementation of the ADT list that expands the size of the array of...
Write an array-based implementation of the ADT list that expands the size of the array of list entries as needed so that the list can always accommodate a new entry. Also reduce the size of the array as needed to accommodate several removals. When the size of the array is greater than 20 and the number of entries in the list is less than half the size of the array, reduce the size of the array so that it is...
Array-Based Linked List Implementation: JAVA Decide how to write the methods with items being stored in...
Array-Based Linked List Implementation: JAVA Decide how to write the methods with items being stored in an array. NOT in linked List. Implement an array-based Linked List in your language. Use double as the item. You need to create a driver includes several items and inserts them in order in a list. Identify the necessary methods in a List Linked implementation. Look at previous Data Structures (stack or queue) and be sure to include all necessary methods. DO NOT USE...
Please make an Array-based implementation of a Binary Tree in Python based on the given file...
Please make an Array-based implementation of a Binary Tree in Python based on the given file below. Make sure to keep the Abstract Data File of the starter code below when building the Array-based implementation. Python Starter Code Given Below: class ArrayBinaryTree(BinaryTree): """Linked representation of a binary tree structure.""" # -------------------------- nested _Node class -------------------------- class _Node: def __init__(self, element, parent=None, left=None, right=None): # -------------------------- nested Position class -------------------------- class Position(BinaryTree.Position): """An abstraction representing the location of a single element."""...
In C++ write an implementation of the ADT sorted list that uses a resizable array (vector...
In C++ write an implementation of the ADT sorted list that uses a resizable array (vector class of C++ STL) to represent the list items.
Question: Write an implementation of the ADT sorted list that uses a resizable array (vector class...
Question: Write an implementation of the ADT sorted list that uses a resizable array (vector class of C++ STL) to represent the list items. Anytime the list becomes full, double the size of the array.
JAVA Write a class for a Stack of characters using a linked list implementation. Write a...
JAVA Write a class for a Stack of characters using a linked list implementation. Write a class for a Queue of characters using a linked list implementation. Write a class for a Queue of integers using a circular array implementation.
This Array implementation allows duplicates. Add a method that searches the array and remove all the...
This Array implementation allows duplicates. Add a method that searches the array and remove all the values in the array that does not have a duplicate. void removeNoDups( ) ( 12 points) For example if array had elements 100 200 100 100 200 400 500 300, once this new method is run it should return 100 200 100 100 200 removing 400, 500 and 300 which do not have duplicate values in the array. So in short this method allows...
This Array implementation allows duplicates. Add a method that searches the array and remove all the...
This Array implementation allows duplicates. Add a method that searches the array and remove all the values in the array that does not have a duplicate. void removeNoDups( ) ( 12 points) For example if array had elements 100 200 100 100 200 400 500 300, once this new method is run it should return 100 200 100 100 200 removing 400, 500 and 300 which do not have duplicate values in the array. So in short this method allows...
Given the following array, write a program in C++ to sort the array using a selection...
Given the following array, write a program in C++ to sort the array using a selection sort and display the number of scores that are less than 500 and those greater than 500. Scores[0] = 198 Scores[3] = 85 Scores[6] = 73 Scores[9] = 989 Scores[1] = 486 Scores[4] = 216 Scores[7] = 319 Scores[2] = 651 Scores[5] = 912 Scores[8] = 846
Write a code in c++ using dynamic array of structure and dynamic array list. Make a...
Write a code in c++ using dynamic array of structure and dynamic array list. Make a dummy list for a company which stores following information about its customers. Customer ID Customer Name Gender Total items purchased Item category 20% discount in percentage of total purchase amount. Use dynamic array to save at least 20 items by dividing them into 3 different categories. Make a dummy list of items that company sells by dividing them into two categorizes. Items has following...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT