Question

JAVA // TO DO: add your implementation and JavaDoc public class SmartArray<T>{    private static final...

JAVA

// TO DO: add your implementation and JavaDoc

public class SmartArray<T>{

   private static final int DEFAULT_CAPACITY = 2;   //default initial capacity / minimum capacity
   private T[] data;   //underlying array

   // ADD MORE PRIVATE MEMBERS HERE IF NEEDED!
  
   @SuppressWarnings("unchecked")
   public SmartArray(){
       //constructor
       //initial capacity of the array should be DEFAULT_CAPACITY
   }

   @SuppressWarnings("unchecked")
   public SmartArray(int initialCapacity){
       // constructor
       // set the initial capacity of the smart array as initialCapacity

       // throw IllegalArgumentException if initialCapacity is smaller than 1
   }
  

   public int size() {  
       //report number of elements in the smart array
       // O(1)
      
       return 0;
   }
      
   public int capacity() {
       //report max number of elements before the next expansion
       // O(1)

       return 0;
   }
  
   @SuppressWarnings("unchecked")
   public void add(int index, T value){
       // insert value at index, shift elements if needed
       // double the capacity if no space is available
       // throw IndexOutOfBoundsException for invalid index
       // O(N) where N is the number of elements in the array
      
       // Note: this method may be used to append items as
       // well as insert items
   }

   public T get(int index){
       // return the item at index
       // throw IndexOutOfBoundsException for invalid index
       // O(1)

       return null;
   }


   public T replace(int index, T value){
       // change item at index to be value  
       // return old item at index
       // throw IndexOutOfBoundsException for invalid index
       // O(1)
      
       // Note: you cannot add new items with this method

       return null;
   }


   @SuppressWarnings("unchecked")
   public T delete(int index){
       // remove and return element at position index
       // shift elements to remove any gap in the array
       // throw IndexOutOfBoundsException for invalid index
      
       // halve capacity if the number of elements falls below 1/4 of the capacity
       // capacity should NOT go below DEFAULT_CAPACITY
      
       // O(N) where N is the number of elements in the list

       return null;
   }

   @SuppressWarnings("unchecked")
   public boolean ensureCapacity(int newCapacity){
       // change the max number of items allowed before next expansion to newCapacity
      
       // capacity should not be changed if:
       // - newCapacity is below DEFAULT_CAPACITY; or
       // - newCapacity is not large enough to accommodate current number of items
      
       // return true if newCapacity gets applied; false otherwise
       // O(N) where N is the number of elements in the array
      
       return false;  
   }


   // --------------------------------------------------------
   // example testing code... edit this as much as you want!
   // --------------------------------------------------------

   // Not required, update for your own testing
   public String toString(){
       // return string representation of DynamicArray
       // update if you want to include more information
       return "SmartArray";
   }

   // Not required, update for your own testing
   public static void main (String args[]){

       //create a smart array of integers
       SmartArray<Integer> nums = new SmartArray<>();
       if ((nums.size() == 0) && (nums.capacity() == 2)){
           System.out.println("Yay 1");
       }

       //append some numbers
       for (int i=0; i<3;i++)
           nums.add(i,i*2);
      
       if (nums.size()==3 && nums.get(2) == 4 && nums.capacity() == 4 ){
           System.out.println("Yay 2");
       }
      
       //create a smart array of strings
       SmartArray<String> msg = new SmartArray<>();
      
       //insert some strings
       msg.add(0,"world");
       msg.add(0,"hello");
       msg.add(1,"new");
       msg.add(3,"!");
      
       //replace and checking
       if (msg.get(0).equals("hello") && msg.replace(1,"beautiful").equals("new")
           && msg.size() == 4 && msg.capacity() == 4 ){
           //System.out.println(msg);
           System.out.println("Yay 3");
       }
      
       //change capacity
       if (!msg.ensureCapacity(0) && !msg.ensureCapacity(3) && msg.ensureCapacity(20)
           && msg.capacity() == 20){
           System.out.println("Yay 4");
       }     

       //delete and shrinking
       if (msg.delete(1).equals("beautiful") && msg.get(1).equals("world")
           && msg.size() == 3 && msg.capacity() == 10 ){
           System.out.println("Yay 5");
       }
   }
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

IF YOU HAVE ANY DOUBTS PLEASE COMMENT BELOW I WILL THERE TO HELP YOU

ANSWER:

CODE:

public class DynamicArray<T>{

  

   private static final int INITCAP = 2; // default initial capacity / minimum capacity

   private T[] storage; // underlying array

   private int size = 0;

   private int capacity = 0;

   // ADD MORE PRIVATE MEMBERS HERE IF NEEDED!

  

   @SuppressWarnings("unchecked")

   public DynamicArray(){

   // constructor

   // initial capacity of the array should be INITCAP

   storage = (T[]) new Object[INITCAP];

   size = 0;

   capacity = INITCAP;

   }

   @SuppressWarnings("unchecked")

   public DynamicArray(int initCapacity){

   // constructor

   // set the initial capacity of the array as initCapacity

   // throw IllegalArgumentException if initCapacity < 1

   if(initCapacity < 1)

       throw new IllegalArgumentException();

   storage = (T[]) new Object[initCapacity];

   size = 0;

   capacity = initCapacity;

   }

   public int size() {

   //report the number of elements in the list

   // O(1)

   return size;

   }

  

   public int capacity() {

   //report the max number of elements before the next expansion

   // O(1)

   return capacity;

     

   }

  

   public T set(int index, T value){

   // change item x at index i to be value

   // return old item at index

   // throw IndexOutOfBoundsException for invalid index

   // O(1)

  

   // Note: you cannot add new items with this method

   if (index < 0 || index >=capacity)

       throw new IllegalArgumentException();

     

   T old = storage[index];

   storage[index] = value;

   return old;

   }

   public T get(int index){

   // return the item at index

   // throw IndexOutOfBoundsException for invalid index

   // O(1)

   if (index < 0 || index >=capacity)

       throw new IllegalArgumentException();

     

   return storage[index];

   }

   @SuppressWarnings("unchecked")

   public boolean add(T value){

   // add value to the end of the list (append)

   // return true

  

   // double the capacity if no space is available

   // amortized O(1)

  

   // Note: Remember... code reuse is awesome...

   if(size==capacity){

          T[] temp = (T[]) new Object[2*capacity];

          for(int i=0 ;i<size; ++i)

           temp[i] = storage[i];

       storage = temp;

       capacity = 2*capacity;

   }

   storage[size] = value;

   size++;

     

   return true;

   }

  

  

   @SuppressWarnings("unchecked")

   public void add(int index, T value){

   // insert value at index, shift elements if needed

   // double the capacity if no space is available

   // throw IndexOutOfBoundsException for invalid index

   // O(N) where N is the number of elements in the list

  

   // Note: this method may be used to append items as

   // well as insert items

     

   if (index < 0)

       throw new IllegalArgumentException();

     

   if(index==capacity || size == capacity){

              T[] temp = (T[]) new Object[2*capacity];

              for(int i=0 ;i<size; ++i)

               temp[i] = storage[i];

           storage = temp;

           capacity = 2*capacity;

   }

     

   for(int k = size-1; k>=index; k--)

       storage[k+1] = storage[k];

     

   storage[index] = value;

     

   size++;

     

     

     

   }

  

  

   @SuppressWarnings("unchecked")

   public T remove(int index){

   // remove and return element at position index

   // shift elements to remove any gap in the list

   // throw IndexOutOfBoundsException for invalid index

  

   // halve capacity if the number of elements falls below 1/3 of the capacity

   // capacity should NOT go below INITCAP

  

   // O(N) where N is the number of elements in the list

     

   if (index < 0 || index >=capacity)

       throw new IllegalArgumentException();

     

   T val = storage[index];

   for(int k = index; k<size; k++)

       storage[k] = storage[k+1];

     

   size--;

     

   if(size <= capacity/3) {

         

       T[] temp = (T[]) new Object[capacity/2];

              for(int i=0 ;i<size; ++i)

               temp[i] = storage[i];

           storage = temp;

           capacity = capacity/2;

   }

     

   return val;

  

   }

  

  

   // --------------------------------------------------------

   // example testing code... edit this as much as you want!

   // --------------------------------------------------------

   // Not required, update for your own testing

   @Override

   public String toString(){

   // return string representation of DynamicArray

   // update if you want to include more information

   return "DynamicArray with size "+size+", capacity "+capacity;

  

   }

  

   public static void main (String args[]){

   // new list?

   DynamicArray<Integer> ida = new DynamicArray<>();

   if ((ida.size() == 0) && (ida.capacity() == 2)){

   System.out.println("Yay 1");

   }

   // adding to the list?

   boolean ok = true;

   for (int i=0; i<3;i++)

   ok = ok && ida.add(i*5);

  

   if (ok && ida.size()==3 && ida.get(2) == 10 && ida.capacity() == 4 ){

   System.out.println("Yay 2");

   }

  

   ida.add(1,-10);

   ida.add(4,100);

   if (ida.set(1,-20)==-10 && ida.get(2) == 5 && ida.size() == 5

   && ida.capacity() == 8 ){

   System.out.println("Yay 3");

   }

  

   // removing from the list?

   if (ida.remove(0) == 0 && ida.remove(0) == -20 && ida.remove(2) == 100

   && ida.size() == 2 && ida.capacity() == 4 ){

   System.out.println("Yay 4");

   }

  

   // remember to tests more things...

   }

}

===================================
See Output


Thanks, PLEASE UPVOTE if helpful

Add a comment
Know the answer?
Add Answer to:
JAVA // TO DO: add your implementation and JavaDoc public class SmartArray<T>{    private static final...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • PLEASE EDIT THE LAST 3 METHODS WHERE I PUT STARS AND DO WHAT THE COMMENTS SAY....

    PLEASE EDIT THE LAST 3 METHODS WHERE I PUT STARS AND DO WHAT THE COMMENTS SAY. THE CODE IS IN JAVA PROGRAMMING LANGUAGE. import java.util.AbstractList; import java.util.List; import java.util.RandomAccess; import java.lang.RuntimeException; import java.util.Arrays; public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess {    protected Object[] data; protected int size; public int size() {     return size; }    private void rangeCheck(int index) {     if (index < 0 || index >= size) throw new IndexOutOfBoundsException(""); }    @SuppressWarnings("unchecked") private E...

  • USE JAVA: Given the Interface Code and the Interface Implementation Code; Write Junit Tests to test...

    USE JAVA: Given the Interface Code and the Interface Implementation Code; Write Junit Tests to test all fuctionality. ------------- Interface code: public interface CustomList { /** * This method should add a new item into the CustomList and should * return true if it was successfully able to insert an item. * @param item the item to be added to the CustomList * @return true if item was successfully added, false if the item was not successfully added (note: it...

  • Java Programming: The following is my code: import java.util.Arrays; public class KWArrayList<E> {    // Data...

    Java Programming: The following is my code: import java.util.Arrays; public class KWArrayList<E> {    // Data fields    /** The default initial capacity */    private static final int INITIAL_CAPACITY = 10;       /** The underlying data array */    private E[] theData;       /** The current size */    private int size = 0;       /** The current capacity */    private int capacity = 0;       @SuppressWarnings("unchecked")    public KWArrayList() {        capacity...

  • Expected OUTPUT: Codes Failed at Test D,E,F. Needs to be fixed: public class Vector<T> { private...

    Expected OUTPUT: Codes Failed at Test D,E,F. Needs to be fixed: public class Vector<T> { private const int DEFAULT_CAPACITY = 10; private T[] data; public int Count { get; private set; } = 0; public int Capacity { get { return data.Length; } }    public Vector(int capacity) { data = new T[capacity]; }    public Vector() : this(DEFAULT_CAPACITY) { } public T this[int index] { get { if (index >= Count || index < 0) throw new IndexOutOfRangeException(); return...

  • Java Write an intersection method for the ResizableArrayBag class. The intersection of two bags is the...

    Java Write an intersection method for the ResizableArrayBag class. The intersection of two bags is the overlapping content of the bags. Intersections are explained in more detail in Chapter 1, #6. An intersecion might contain duplicates. The method should not alter either bag. The current bag and the bag sent in as a parameter should be the same when the method ends. The method header is: public BagInterface<T> intersection(ResizableArrayBag <T> anotherBag) Example: bag1 contains (1, 2, 2, 3) bag2 contains...

  • Use JAVA language. public class DynamicArray2 { private String[] data; // the backing array private int...

    Use JAVA language. public class DynamicArray2 { private String[] data; // the backing array private int virtualArrayLength; // the number of elements in the dynamic array // Throws an IndexOutOfBoundsException if i is not a valid index // for adding to the dynamic array, otherwise inserts s at index i. // Elements can be added from index 0 to this.size(). public void add(int i, String s) { // If there is no room for s in data, create a new...

  • how would I complete this code without calling any built-in java collection framework classes like ArrayList,...

    how would I complete this code without calling any built-in java collection framework classes like ArrayList, LinkedList, etc? import java.util.Iterator; class CallStack<T> implements Iterable<T> { // You'll want some instance variables here public CallStack() { //setup what you need } public void push(T item) { //push an item onto the stack //you may assume the item is not null //O(1) } public T pop() { //pop an item off the stack //if there are no items on the stack, return...

  • Suppose that you have several numbered billiard balls on a pool table. The smallest possible number...

    Suppose that you have several numbered billiard balls on a pool table. The smallest possible number on the ball is “1”. At each step, you remove a billiard ball from the table. If the ball removed is numbered n, you replace it with n balls randomly numbered less than n. For example, if you remove the “5” ball, you replace it with balls numbered “2”, “1”, “1”, “4”, and “3”, where numbers 2, 1, 1, 4, and 3 were randomly...

  • Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an ...

    Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an array. Implement all methods in ArrayStack class using resizable array strategy, i.e. usedoubleArray() Must throw StackException during exception events in methods:    peek(), pop(), ArrayStack(int initialCapacity) Do not change or add data fields Do not add new methods */ import java.util.Arrays; public class Arraystack«Т> implements Stack!nterface«T> private TI stack;// Array of stack entries private int topIndex; /7 Index of top entry private static...

  • Java Programming: The following is my code: public class KWSingleLinkedList<E> {    public void setSize(int size)...

    Java Programming: The following is my code: public class KWSingleLinkedList<E> {    public void setSize(int size)    {        this.size = size;    }    /** Reference to list head. */    private Node<E> head = null;    /** The number of items in the list */    private int size = 0;       /** Add an item to the front of the list.    @param item The item to be added    */    public void addFirst(E...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT