Question

In: Computer Science

For the first part of this lab, copy your working ArrayStringList code into the GenericArrayList class.(already...

For the first part of this lab, copy your working ArrayStringList code into the GenericArrayList class.(already in the code) Then, modify the class so that it can store any type someone asks for, instead of only Strings. You shouldn't have to change any of the actual logic in your class to accomplish this, only type declarations (i.e. the types of parameters, return types, etc.)

Note:

In doing so, you may end up needing to write something like this (where T is a generic type):

T[] newData = new T[capacity]; 

...and you will find this causes a compiler error. This is because Java dislikes creating new objects of a generic type. In order to get around this error, you can write the line like this instead:

T[] new Data = (T[]) new Object[capacity] 

This creates an array of regular Objects which are then cast to the generic type. It works and it doesn't anger the Java compiler. How amazing!

Once you're done, screenshot or save your code for checkin later.

For the second part of the lab, modify your GenericArrayList so that it can store any type that is comparable to a Point. Remember the Point and Point3D classes? Both of those implement the Comparable<Point> interface, so they both can compared to a Point. In fact, they are the only classes that can be compared to a Point, so after modifying your GenericArrayList, it should only be able to contain these two classes.

In both parts, test your classes by following the directions in the comments. They will ask you to uncomment some code and look for a specific result.

public class GenericArrayList {

/* YOUR CODE HERE

   * Copy your code from your ArrayStringList class, and place it within

   * this class.

   *

   * Only copy the code you filled out! Don't copy the main method.

   */

   // Place code here

public class ArrayStringList {

private String[] data;

private int size;

private void resizeData(int newSize) {

String[] str = new String[newSize];

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

str[i] = data[i];

}

data=str;

}

public ArrayStringList(int initialCapacity) {

data = new String[initialCapacity];

size = 0;

}

public void add(String str) {

if(size < data.length) {

data[size] = str;

size++;

} else {

resizeData(2 * data.length);

data[size] = str;

size++;

}

}

public void add(int index, String str) {

if(index < data.length && index >= 0) {

data[index] = str;

size++;

}

}

public String get(int index) {

if(index < data.length && index >= 0) {

return data[index];

}

return null;

}

public void remove(int index) {

if(index < data.length && index >= 0) {

for(int i = index; i < data.length; i++) {

if((i + 1) < size) {

data[i] = data[i + 1];

}

}

size--;

}

}

public int size() {

return size;

}

public boolean contains(String str) {

for(int i = 0; i < data.length; i++) {

if(str.equals(data[i])) {

return true;

}

}

return false;

}

public static void main(String[] args) {

/* PART 1:

   * Modify the GenericArrayList above so that it can store *any* class,

   * not just strings.

   * When you've done that, uncomment the block of code below, and see if

   * it compiles. If it does, run it. If there are no errors, you did

   * it right!

   */

GenericArrayList<Point> pointList = new GenericArrayList<Point>(2);

pointList.add(new Point(0, 0));

pointList.add(new Point(2, 2));

pointList.add(new Point(7, 0));

pointList.add(new Point(19.16f, 22.32f));

pointList.remove(0);

Point p = pointList.get(2);

if (p.x != 19.16f && p.y != 22.32f) {

throw new AssertionError("Your GenericArrayList compiled properly "

+ "but is not correctly storing things. Make sure you didn't "

+ "accidentally change any of your ArrayStringList code, aside "

+ "from changing types.");

}

GenericArrayList<Float> floatList = new GenericArrayList<Float>(2);

for (float f = 0.0f; f < 100.0f; f += 4.3f) {

floatList.add(f);

}

float f = floatList.get(19);

System.out.println("Hurray, everything worked!");

  

/* PART 2:

   * Now, modify your GenericArrayList again so that it can only store

   * things that are comparable to a Point.

   *

   * If you don't know how to do this, reference zybooks and your textbook

   * for help.

   *

   * When you are ready to test it, uncomment the code above and run the

   * code below.

   */

/*

GenericArrayList<Point> pointList = new GenericArrayList<Point>(2);

GenericArrayList<Point3D> pointList3D = new GenericArrayList<Point3D>(3);

pointList.add(new Point(0, 0));

pointList.add(new Point(2, 2));

pointList.add(new Point(7, 0));

pointList.add(new Point(19.16f, 22.32f));

pointList3D.add(new Point3D(1.0f, 2.0f, 3.0f));

pointList3D.add(new Point3D(7.3f, 4, 0));

Point p = pointList.get(2);

Point3D p3 = pointList3D.get(0);

// You should get a compilation error on this line!

GenericArrayList<Float> floatList = new GenericArrayList<Float>(2);

*/

}

}

}

Solutions

Expert Solution

First part:

public class GenericArrayList<T> {

    private T[] data;
    private int size;

    private void resizeData(int newSize) {
        data = (T[]) new Object[newSize];
        for (int i = 0; i < size; i++) {
            data[i] = data[i];
        }
    }

    public GenericArrayList(int initialCapacity) {
        data = (T[]) new Object[initialCapacity];
        size = 0;
    }

    public void add(T str) {
        if (size < data.length) {
            data[size] = str;
            size++;
        } else {
            resizeData(2 * data.length);
            data[size] = str;
            size++;
        }
    }

    public void add(int index, T str) {
        if (index < data.length && index >= 0) {
            data[index] = str;
            size++;
        }
    }

    public T get(int index) {
        if (index < data.length && index >= 0) {
            return data[index];
        }
        return null;
    }

    public void remove(int index) {
        if (index < data.length && index >= 0) {
            for (int i = index; i < data.length; i++) {
                if ((i + 1) < size) {
                    data[i] = data[i + 1];
                }
            }
            size--;
        }
    }

    public int size() {
        return size;
    }

    public boolean contains(T str) {
        for (int i = 0; i < data.length; i++) {
            if (str.equals(data[i])) {
                return true;
            }
        }

        return false;
    }
}

**************************************************
Second Part:

public class GenericArrayList<T extends Point> {

    private T[] data;
    private int size;

    private void resizeData(int newSize) {
        data = (T[]) new Object[newSize];
        for (int i = 0; i < size; i++) {
            data[i] = data[i];
        }
    }

    public GenericArrayList(int initialCapacity) {
        data = (T[]) new Object[initialCapacity];
        size = 0;
    }

    public void add(T str) {
        if (size < data.length) {
            data[size] = str;
            size++;
        } else {
            resizeData(2 * data.length);
            data[size] = str;
            size++;
        }
    }

    public void add(int index, T str) {
        if (index < data.length && index >= 0) {
            data[index] = str;
            size++;
        }
    }

    public T get(int index) {
        if (index < data.length && index >= 0) {
            return data[index];
        }
        return null;
    }

    public void remove(int index) {
        if (index < data.length && index >= 0) {
            for (int i = index; i < data.length; i++) {
                if ((i + 1) < size) {
                    data[i] = data[i + 1];
                }
            }
            size--;
        }
    }

    public int size() {
        return size;
    }

    public boolean contains(T str) {
        for (int i = 0; i < data.length; i++) {
            if (str.equals(data[i])) {
                return true;
            }
        }

        return false;
    }
}

**************************************************

I have tried to answer your question to best of my efforts. However, if you still face any issues in the answer, please let me know via the comment section. Your feedback will imporve as well as encourage me to keep up the good work.

If i was able to help you, then please provide me an upvote(thumbs up). Thanks!


Related Solutions

. On your first day working in a biochemistry research lab, you are asked to prepare...
. On your first day working in a biochemistry research lab, you are asked to prepare 500 mL of a 0.15 M sodium phosphate buffer solution at pH 6.5. Your lab contains stock solutions of H3PO4, NaH2PO4, Na2HPO4, and Na3PO4, each at 0.5 M, as well as plenty of double-distilled water.(a). (6 points) What do you mix and in what amounts in order to prepare the desired buffer?
Part 2– R work (must be done in R) Copy and paste your R code and...
Part 2– R work (must be done in R) Copy and paste your R code and output into a word document, along with your written answers to the questions, and upload to Canvas.   Follow these instructions to import the necessary dataset: Before opening the dataset needed for this problem, you’ll need to call the “car”package.  Run the following line of code: > library(car) Now you can import the “Prestige” dataset and use it to answer the question below. Name the data...
Create a class called Height Copy the code for Height given below into the class. Remember...
Create a class called Height Copy the code for Height given below into the class. Remember – test the methods as you go Take a few minutes to understand what the class does. There are comments where you will have to be changing code. A list of changes are given Change the setFeet and setInches mutators to make sure the height and width will not be less than 0, no matter what is passed in to it Change constructor that...
Your first lab is to create a simple class that emulates some mathematical functions in relation...
Your first lab is to create a simple class that emulates some mathematical functions in relation to complex numbers. A complex number is a number of the form a + bi, where a is a real number and bi is an imaginary number. Create a class Complex having two private data members real and imag of type double. The class has two constructors, one default (no parameters) and one whose parameters initialize the instance variables. It also need the following...
JAVA CODE BEGINNERS, I already have the demo code included Write a Bottle class. The Bottle...
JAVA CODE BEGINNERS, I already have the demo code included Write a Bottle class. The Bottle will have one private int that represents the countable value in the Bottle. Please use one of these names: cookies, marbles, M&Ms, pennies, nickels, dimes or pebbles. The class has these 14 methods: read()(please use a while loop to prompt for an acceptable value), set(int), set(Bottle), get(), (returns the value stored in Bottle), add(Bottle), subtract(Bottle), multiply(Bottle), divide(Bottle), add(int), subtract(int), multiply(int), divide(int), equals(Bottle), and toString()(toString()...
Using the first code of this lab (Figure 1), write a code that displays the status...
Using the first code of this lab (Figure 1), write a code that displays the status of a push button on the LCD, that is, when you press it you should see “Pushed” on the LCD and when you release it, you should see “Released” #include <LiquidCrystal.h> // initialize the library with the numbers of the interface pins LiquidCrystal lcd(12, 11, 5, 4, 3, 2); void setup() { // set up the LCD's number of columns and rows: lcd.begin(16, 2);...
Using Java This is two-part question, but I have already completed the first part and just...
Using Java This is two-part question, but I have already completed the first part and just need help with the second. Here I will provide both questions and my answer to the first part: Part I Question: Write a class called Dog that contains instance data that represents the dog’s name, breed, weight, birthdate, and medical history. Define the Dog constructor to accept and initialize instance data (begin the medical history with an empty line). Include accessor and mutator methods...
Write a MATLAB code to obtain the following. Keep your code commented whenever required. Copy your...
Write a MATLAB code to obtain the following. Keep your code commented whenever required. Copy your source code and command widow outcomes and screen shots of any plots in your solution. Develop three functions for temperature-conversion. Create a function called F_to_K that converts and return temperatures in Fahrenheit to Kelvin and store results in ‘F_to_K2.txt’. Create a function called C_to_R that converts and return temperatures in Celsius to Rankine and store results in ‘C_to_R2.txt’. Create a function called C_to_F that...
Write a MATLAB code to obtain the following. Keep your code commented whenever required. Copy your...
Write a MATLAB code to obtain the following. Keep your code commented whenever required. Copy your source code and command widow outcomes and screen shots of any plots in your solution. Write a user defined function ‘My_FunctionGen’. It accepts, the time vector ‘t’ with 8000 uniformly spaced values within the range of 0 to 8, Frequecy scalars ‘f1<100H’ and ‘f2<80Hz’ and Amplitude scalars ‘A1’, ‘A2’ and ‘A3’ as input arguments. It delivers x1, x2 and x3 and x4 as outputs...
Write a MATLAB code to obtain the following. Keep your code commented whenever required. Copy your...
Write a MATLAB code to obtain the following. Keep your code commented whenever required. Copy your source code and command widow outcomes and screen shots of any plots in your solution. Generate the following vectors and also implement the Table-1 operations-map by employing the switch statement and an appropriate loop. Generate a vector ‘DEC1’ as follow. DEC1 = 5     1     3     0     2    5     0     2 Concatenate vector ‘DEC1’ eight times in order to obtain a bigger row vector ‘DEC’...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT