Question

In: Computer Science

CSC202-001 Clark Problem 1: For this class Java’s ArrayList is used to store a collection of...

CSC202-001 Clark

Problem 1:

For this class Java’s ArrayList is used to store a collection of different elements. Please design and implement your own array-based version of MyArrayList that stores items of type

String and supports the following operations:

+MyArrayList()

//a constructor that creates an empty array list

+emptyHere() : Boolean

// Determines whether the list is empty or not

+sizeHere() : integer

// Returns the # of items stored in the array list

+add(in item : String) : void

// Appends the specified elements to the list

+removeMe(in item : String) : void

// Removes the first occurrence of the specified element from the list (if it is present)

+get(in index : integer) : String

// Returns the element at the specified index from the list. The list will remain unmodified.

+removeAll() : void

// Removes all the items in the list here

2. Your implementation should contain two class attributes. The first, called firstArray, is an

array of String. The second, called size, is of type int. The firstArray class attribute

should be created on the call to the constructor and initially have a size of two (2). The

constructor should also initialize the size attribute to zero (0).

3. On each call to add, check to see if firstArray is full. If adding the new element would

cause the array to overflow, then do the following:

a. please create a new bigger array that is twice the size of original array;

b. copy the whole contents of the original array to new array;

c. add the new element to the new array; and

d. reassign firstArray to reference the new array correctly

4. On each call to remove, check to see if firsttArray is less than or equal to a quarter full. If

removing the specified element would cause the array to be less than 25% full, then

a. remove the selected element from original array;

b. create a new smaller array that is half the size of the original array;

c. copy the whole contents of the original array to the new array; and

d. reassign firstArray to reference this new array.

5. Your implementation should reset the size of firstArray back to size 2 if all the elements

are removed (i.e. removeAll() is called).

6. To make sure that your implementation is working correctly, you will create an

MyArrayListException class. This exception needs to be thrown if any attempt is

made to access an illegal index within the lstArray attribute. Create a file called

MyArrayListException.java containing the following code:

public class MyArrayListException extends RuntimeException {

public MyArrayListException(String s) {

super(s);

}

}

Your submission should NOT contain a main method, the code implementing MyArrayListException, or any extra testing code

You may write any private helper methods, as needed.

You may use notes and help from internet.

Solutions

Expert Solution

Please up vote ,comment if any query . Thanks for Question . Be safe.

Note : check attached image for output ,code compiled and tested in java netbeans ide.

Attached a main class to test program , do not attach it for submission as your question stats.

Program Plan :

  1. add method () this will add item to array
  2. if array alread full it will create a new array of double size and copy new array into old array
  3. removeMe first it run a loop to find item from array
  4. if item found than it shift left all element to left and decrement size by 1
  5. if item found we have index so now check percentage of array size full
  6. if less than or equal to 25% than create a new array of half size and copy element and assign to old array .
  7. get method check if index less than size return item else throw myArrayList exception "Invalid Index."

Program : *****************************MyArrayList.java**************************************


import java.util.Arrays;

//class MyArrayList
public class MyArrayList {
    private String []firstArray; //Array of string size not assigned
    private int size; //size

    public MyArrayList() {
       this.firstArray=new String[2]; //initial size of array is 2
        this.size=0; //size (number of elements is zero )
    }
    //if size ==0 return true else false
    public boolean emptyHere()
    {
        return (this.size==0);
    }
  
    public int sizeHere()
    {
        return this.size;//return number of item in array
    }
    public void add(String item) //add item to array
    {
        if(this.firstArray.length==size) //if size equal to array length
        {
            String []newArray; //new array
            //copy old value in new array and size=oldsize*2
            newArray = Arrays.copyOf(this.firstArray,(this.firstArray.length*2));
            newArray[size]=item; //add item
            this.firstArray=Arrays.copyOf(newArray,newArray.length); //reassign to old array
            ++size; //increment size
          
        }
        else //if size not equal to array length
        {
            this.firstArray[size]=item; //add item and increment size
            ++size;
        }
      
    }
  
    public void removeMe(String item) //remove
    {
        int itemIndex=-1; //index of item is -1
        for(int i=0;i<this.size;i++)
        {
            if(this.firstArray[i]==item) //if item found
            {
                itemIndex=i;//run a loop from found item to size
                for(int j=itemIndex;j<size-1;j++)
                {
                    this.firstArray[j]=this.firstArray[j+1];
                }
                --this.size; //decrement size
                break; //break from loop
            }
        }
      
        if(itemIndex!=-1) //if item found we have index in itemIndex
        {
            int newSize=(size)*100/this.firstArray.length; //get percentage of size
            if(newSize<=25) //if less than 25 or equal
            {
                String []newArray; //new array
                newArray = Arrays.copyOf(this.firstArray,(this.firstArray.length/2)); //new array of half size
                this.firstArray=Arrays.copyOf(newArray,newArray.length); //copy values to old array

            }
        }
      
   
    }
  
    public String get(int index)
    {
        if(index>=size) //index > = size throw exception
            throw new MyArrayListException("Invalid Index.");
        else
            return this.firstArray[index]; //return item
    }
  
    public void removeAll() //size=0
    {
        this.size=0;
        this.firstArray=Arrays.copyOf(firstArray, 2); //length is 2
    }
  
  
  
  
  
}

Program : ************************MyArrayListException.java*********************************


//MyArrayListException class
public class MyArrayListException extends RuntimeException {

    public MyArrayListException(String s) //passed string
    {
         super(s);
    }

}

Program : ***************************Main.java***********************************


public class Main {


    public static void main(String[] args) {
      
        MyArrayList obj=new MyArrayList(); //object creating
        System.out.println(obj.emptyHere()); //true if empty
        System.out.println(obj.sizeHere()); //get size
        obj.add("tinku"); //add item
        System.out.println(obj.emptyHere()); //now false
        System.out.println(obj.sizeHere()); //size=1
        obj.add("jangid"); //add jangid
        System.out.println(obj.emptyHere()); //false
        System.out.println(obj.sizeHere()); //2
        obj.add("jaipur"); //add
        System.out.println(obj.emptyHere()); //false
        System.out.println(obj.sizeHere()); //3
      
        obj.removeMe("tinku"); //remove
        System.out.println(obj.emptyHere()); //false
        System.out.println(obj.sizeHere()); //2
      
        obj.removeMe("jangid"); //remove
        System.out.println(obj.emptyHere()); //false
        System.out.println(obj.sizeHere()); //size 1
      
        obj.removeMe("jaipur"); //remove
        System.out.println(obj.emptyHere()); //true
        System.out.println(obj.sizeHere()); //0
      
        obj.removeAll(); //remove all
        System.out.println(obj.emptyHere()); //true
        System.out.println(obj.sizeHere()); //0
      
    }
  
}

Output :

Please up vote ,comment if any query . Be Safe.


Related Solutions

HashMap is a Map based collection class that is used for storing Key & value pairs,...
HashMap is a Map based collection class that is used for storing Key & value pairs, it is denoted as HashMap<Key, Value> or HashMap<K, V>. This class makes no guarantees as to the order of the map. It is similar to the Hashtable class except that it is unsynchronized and permits nulls(null values and null key). 5.Write a Java program to test if a map contains a mapping for the specified key.a.Add values in the Hash mapb.Printthe mapc.Check for a...
Econ 178-001 International Trade Problem Set 1 All of the questions in this assignment refer to...
Econ 178-001 International Trade Problem Set 1 All of the questions in this assignment refer to material found in Chapter 9 on tariffs and quotas. 1. Home is a small country with a demand curve for wheat described by QD = 1000 – 100P. Its supply curve is described by QS = 100P. *please part e-h only* a. Graph this market. What is the equilibrium price and quantity in the absence of trade? b. Calculate the consumer and producer surplus...
Develop the getSuggestions(ArrayList wordCountList) method as the base method of the class. Develop the countWords(ArrayList wordList)...
Develop the getSuggestions(ArrayList wordCountList) method as the base method of the class. Develop the countWords(ArrayList wordList) method to find the frequencies of all words in the text file. Develop the getWordList(File[] fileArray) method to get all words in the text file. Ignore the words that have 3 or less characters. Your customer wants you to develop a method that will find the sentences that contain a specific word. This is basically a word search, but your customer needs the list...
import java.util.*; class Main { static ArrayList<String> list; public static List<String> createList(ArrayList<String> arrayList) { list =...
import java.util.*; class Main { static ArrayList<String> list; public static List<String> createList(ArrayList<String> arrayList) { list = arrayList; return list; } public static void printList(ArrayList<String> arrayList) { System.out.println("Printing in 4 ways\n"); // 1 System.out.println(arrayList); //2 for(String s:arrayList) System.out.print(s+" "); System.out.println(); //3 System.out.println(Arrays.deepToString(list.toArray())); //4 for(int i=0;i<arrayList.size();i++) System.out.print(arrayList.get(i)+" "); System.out.println(); } public static void filterList(ArrayList<String> arrayList) { System.out.println("Filtered in 2 ways\n"); ArrayList<String> copyArrayList = arrayList; //1 for(int i=0;i<arrayList.size();i++) { if(arrayList.get(i).contains("chuck")) { arrayList.remove(i); i--; } } System.out.println(arrayList); //2 copyArrayList.removeIf(str -> str.contains("chunk")); System.out.println(copyArrayList); }   ...
***Given a class called Student and a class called Course that contains an ArrayList of Student....
***Given a class called Student and a class called Course that contains an ArrayList of Student. Write a method called dropStudent() as described below. Refer to Student.java below to learn what methods are available.*** Course.java import java.util.*; import java.io.*; /****************************************************** * A list of students in a course *****************************************************/ public class Course{ /** collection of Students */ private ArrayList<Student> roster; /***************************************************** Constructor for objects of class Course *****************************************************/ public Course(){ roster = new ArrayList<Student>(); } /***************************************************** Remove student with the...
class Company uses an ArrayList of class Employee to manage its employees. Your job is to...
class Company uses an ArrayList of class Employee to manage its employees. Your job is to create two classes , Company and Employee, with appropriate instance fields, constructors, and methods as been described in the set of questions that follows . A sample use case of the classes is shown below: public class CompanyTester{ public static void main(String[] args){ Company myCompany = new Company(); myCompany.add( new Employee("james","gasling")); myCompany.add( new Employee("bill","gate")); myCompany.add( new Employee("dennis","ritchie")); System.out.println(myCompany); } } The sample output of...
JAVA In this PoD you will use an ArrayList to store different pet names (there are...
JAVA In this PoD you will use an ArrayList to store different pet names (there are no repeats in this list). This PoD can be done in your demo program (where your main method is) – you don’t have to create a separate class for today. Details Create an arraylist of Strings, then using a Scanner object you will first read in a number that will tell you how many pet names (one word) you will add to the arraylist....
Step 4: Create a class called BabyNamesDatabase This class maintains an ArrayList of BabyName objects. Instance...
Step 4: Create a class called BabyNamesDatabase This class maintains an ArrayList of BabyName objects. Instance Variables Declare an ArrayList of BabyName objects. Constructor public BabyNamesDatabase () - instantiate the ArrayList of BabyName objects. You will not insert the items yet. This method will be one line of code. Mutator Methods public void readBabyNameData(String filename) - open the provided filename given as input parameter, use a loop to read all the data in the file, create a BabyName object for...
Class Design – IntList (A.k.a. ArrayList (v0.0)) Let’s build a useful class that wraps up an...
Class Design – IntList (A.k.a. ArrayList (v0.0)) Let’s build a useful class that wraps up an array of integers. This class will store two data items; one an array of integers, and the other a counter to track the number of actual elements in the list. Start by defining a new class called IntList and copying the main driver code included below or in IntList.java. Then, add each of the following functions and data items indicated in the member sections....
Implement a class named Parade using an ArrayList, which will manage instances of class Clown. Each...
Implement a class named Parade using an ArrayList, which will manage instances of class Clown. Each Clown only needs to be identified by a String for her/his name. Always join a new Clown to the end of the Parade. Only the Clown at the head of the Parade (the first one) can leave the Parade. Create a test application to demonstrate building a parade of 3 or 4 clowns (include your own name), then removing 1 or 2, then adding...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT