Question

JAVA PROGRAMMING PLEASE This lab has three parts: Create an ArrayList class. Create a LinkedList class....

JAVA PROGRAMMING PLEASE

This lab has three parts:

  1. Create an ArrayList class.
  2. Create a LinkedList class.
  3. Print out the results after testing each of the methods in both of the classes and solving a simple problem with them.

Task 1 – ArrayList Class

Create an ArrayList class. This is a class that uses an internal array, but manipulates the array so that the array can be dynamically changed. This class should contain a default and overloaded constructor, where the default constructor creates an empty array and the overloaded constructor creates one with a size specified by the parameter.

There should also be a method that adds new elements to the array, which handles resizing and creation of the array if needed. As well as a method to remove elements from the array, which also handles resizing if needed. Finally, there should be a method that is able to retrieve an element at a given position in the internal array.

Task 2 – LinkedList Class

Create a LinkedList class. This is a class that uses references to create a list like structure. This class should have a default constructor that creates an empty list.

We will also need a method that adds elements to the list and handles resizing and creation if needed. There should be a removal method and a method that gets elements at any given point in the list.

Task 3 – The Tester Class

            Create a Tester Class, with a Main method. In the Main method, create one ArrayList and LinkedList object each. Use their addition, removal and get methods and show the results by printing the lists before and after each method call. Use user input to populate the lists, with at most ten inputs. After testing the methods, create two new methods, one that takes an ArrayList and one that takes in a LinkedList, and returns the sum of all the elements inside of each.

∃ Some Sample Output:

ArrayList Portion:

Enter a number: 5

Are you done entering numbers (y/n)? n

Enter a number: 9

Are you done entering numbers (y/n)? n

Enter a number: 11

Are you done entering numbers (y/n)? n

Enter a number: 7

Are you done entering numbers (y/n)? y

Initial contents of the list: 5, 9, 11, 7

Contents before adding another item: 5, 9, 11, 7

Please enter another number to add: 21

Contents after adding another item: 5, 9, 11, 7, 21

Contents before removing an item: 5, 9, 11, 7, 21

Please enter the index of the element to remove: 2

Contents after removing an item: 5, 9, 7, 21

Contents before retrieving a value from the list: 5, 9, 7, 21

Please enter the index of the element to retrieve: 0

Element at position 0 is: 5

Contents after retrieving a value from the list: 5, 9, 7, 21

Assume similar input for the LinkedList Portion.

Sum of all items in the ArrayList: 42

Sum of all items in the LinkedList: 42

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

IList.java

public interface IList<T> {

  void Add(T value);

  void Add(T value, int index);

  T Get(int index);

  T Remove();

  T Remove(int index);

  void Set(T value, int index);

  int getSize();

}

ArrayList.java

import java.util.Arrays;

public class ArrayList<T> implements IList<T> {

  private Object[] array;

  public int getSize() {

    return array.length;

  }

  public ArrayList() {

    array = new Object[0];

  }

  public ArrayList(int size) {

    array = new Object[size];

  }

  public void Add(T value) {

    Add(value, array.length);

  }

  public void Add(T value, int index) {

    if (index > array.length)

      throw new IndexOutOfBoundsException();

    array = Arrays.copyOf(array, array.length + 1);

    for (int i = index; i < array.length - 1; i++) {

      // shifting ahead

      array[i + 1] = array[i];

    }

    array[index] = value;

  }

  public void Set(T value, int index) {

    if (index >= array.length)

      throw new IndexOutOfBoundsException();

    array[index] = value;

  }

  public T Get(int index) {

    @SuppressWarnings("unchecked")

    final T t = (T) array[index];

    return t;

  }

  public T Remove(int index) {

    if (index >= array.length)

      throw new IndexOutOfBoundsException();

    var value = Get(index);

    var lastValue = array[array.length - 1];

    array = Arrays.copyOf(array, array.length - 1);

    for (int i = index; i < array.length - 1; i++) {

      // shifting behind

      array[index] = array[index + 1];

    }

    array[array.length - 1] = lastValue;

    return value;

  }

  public T Remove() {

    return Remove(array.length - 1);

  }

}

LinkedList.java

public class LinkedList<T> implements IList<T> {

  class Value<E> {

    public E value;

    public Value<E> next;

  }

  Value<T> head;

  private int Size = 0;

  public int getSize() {

    return Size;

  }

  public LinkedList() {

  }

  public LinkedList(int size) {

    head = new Value<T>();

    var last = head;

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

      last.next = new Value<T>();

      last = last.next;

    }

    Size = size;

  }

  private Value<T> gotoPosition(int index) {

    int currentIndex = 0;

    var last = head;

    while (last.next != null && currentIndex < index) {

      last = last.next;

      currentIndex++;

    }

    if (currentIndex != index) {

      throw new IndexOutOfBoundsException();

    }

    return last;

  }

  public void Add(T value) {

    Add(value, Size);

  }

  public void Add(T value, int index) {

    if (head == null && index == 0) {

      head = new Value<T>();

      head.value = value;

      Size++;

      return;

    }

    if (index == Size) {

      index--;

    }

    var last = gotoPosition(index);

    var newNode = new Value<T>();

    newNode.value = value;

    newNode.next = last.next;

    last.next = newNode;

    Size++;

  }

  public T Get(int index) {

    var last = gotoPosition(index);

    return last.value;

  }

  public T Remove() {

    return Remove(Size - 1);

  }

  public T Remove(int index) {

    int currentIndex = 0;

    var last = head;

    var secondLast = last;

    while (currentIndex != index && last.next != null) {

      secondLast = last;

      last = last.next;

      currentIndex++;

    }

    if (currentIndex == index) {

      var value = last.value;

      secondLast.next = last.next;

      Size--;

      return value;

    } else {

      throw new IndexOutOfBoundsException();

    }

  }

  public void Set(T value, int index) {

    var last = gotoPosition(index);

    last.value = value;

  }

}

TesterClass.java

import java.text.MessageFormat;

import java.util.Scanner;

public class TesterClass {

  static Scanner in;

  public static void main(String[] args) {

    in = new Scanner(System.in);

    System.out.println("Testing array list");

    ArrayList<Integer> arrayList = new ArrayList<>();

    TestList(arrayList);

    System.out.println(MessageFormat.format("Sum of all items in the ArrayList: {0}", getSum(arrayList)));

    System.out.println("Testing linked list");

    LinkedList<Integer> linkedList = new LinkedList<>();

    TestList(linkedList);

    System.out.println(MessageFormat.format("Sum of all items in the LinkedList: {0}", getSum(linkedList)));

    in.close();

  }

  public static void TestList(IList<Integer> list) {

    getUserInput(list);

    System.out.print("Initial content of list: ");

    printList(list);

    System.out.print("Contents before adding another item: ");

    printList(list);

    System.out.print("Please enter another number to add: ");

    list.Add(Integer.parseInt(in.nextLine()));

    System.out.print("Contents after adding another item: ");

    printList(list);

    System.out.print("Contents before removing an item: ");

    printList(list);

    System.out.print("Please enter the index of the element to remove: ");

    list.Remove(Integer.parseInt(in.nextLine()));

    System.out.print("Contents after removing an item: ");

    printList(list);

    System.out.print("Contents before retrieving a value from the list: ");

    printList(list);

    System.out.print("Please enter the index of the element to retrieve: ");

    int index = Integer.parseInt(in.nextLine());

    System.out.println(MessageFormat.format("Element at position {0} is: {1}", index, list.Get(index)));

    System.out.print("Contents after retrieving a value from the list: ");

    printList(list);

  }

  static void printList(IList<Integer> list) {

    for (int i = 0; i < list.getSize(); i++) {

      System.out.print(list.Get(i) + " ");

    }

    System.out.println();

  }

  static void getUserInput(IList<Integer> list) {

    boolean doneEntering = false;

    int count = 0;

    while (!doneEntering && count < 10) {

      System.out.print("Enter a number:");

      list.Add(Integer.parseInt(in.nextLine()));

      System.out.print("Are you done entering numbers (y/n)? ");

      doneEntering = in.nextLine().equals("y") ? true : false;

      ++count;

    }

  }

  static int getSum(IList<Integer> list) {

    int sum = 0;

    for (int i = 0; i < list.getSize(); i++) {

      sum += list.Get(i);

    }

    return sum;

  }

}

Output

Testing array list
Enter a number:5
Are you done entering numbers (y/n)? n
Enter a number:9
Are you done entering numbers (y/n)? n
Enter a number:11
Are you done entering numbers (y/n)? n
Enter a number:7
Are you done entering numbers (y/n)? y
Initial content of list: 5 9 11 7
Contents before adding another item: 5 9 11 7
Please enter another number to add: 21
Contents after adding another item: 5 9 11 7 21
Contents before removing an item: 5 9 11 7 21
Please enter the index of the element to remove: 2
Contents after removing an item: 5 9 7 21
Contents before retrieving a value from the list: 5 9 7 21
Please enter the index of the element to retrieve: 0
Element at position 0 is: 5
Contents after retrieving a value from the list: 5 9 7 21
Sum of all items in the ArrayList: 42
Testing linked list
Enter a number:5
Are you done entering numbers (y/n)? n
Enter a number:9
Are you done entering numbers (y/n)? n
Enter a number:11
Are you done entering numbers (y/n)? n
Enter a number:7
Are you done entering numbers (y/n)? y
Initial content of list: 5 9 11 7
Contents before adding another item: 5 9 11 7
Please enter another number to add: 21
Contents after adding another item: 5 9 11 7 21
Contents before removing an item: 5 9 11 7 21
Please enter the index of the element to remove: 2
Contents after removing an item: 5 9 7 21
Contents before retrieving a value from the list: 5 9 7 21
Please enter the index of the element to retrieve: 0
Element at position 0 is: 5
Contents after retrieving a value from the list: 5 9 7 21
Sum of all items in the LinkedList: 42

Hope this helps :)

Add a comment
Know the answer?
Add Answer to:
JAVA PROGRAMMING PLEASE This lab has three parts: Create an ArrayList class. Create a LinkedList class....
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
  • Solve the following LinkedList problems. You can use the LinkedList class from the previous lab. Write...

    Solve the following LinkedList problems. You can use the LinkedList class from the previous lab. Write the following methods for the LinkedList class Problem 1: Write a method that deletes the first half of the list. Problem 2: Write a method that deletes the second half of the list. Problem 3: Write a method that deletes every other element in the list. Problem 4: Write a method that, given a second LinkedList, creates and returns a third list containing all...

  • Java Create a class named OrderedList. It will use a LinkedList of integers as its attribute....

    Java Create a class named OrderedList. It will use a LinkedList of integers as its attribute. The constructor will simply create an empty list. This will be a different LinkedList, as all of the items will be in ascending numerical order. That means items will not necessarily be placed at the end of the list, but placed where it should be located. Note that the iterator simply uses the next() method, so if you use the iterator to find the...

  • Add the following methods to the ArrayList class that we wrote during lecture. You may call...

    Add the following methods to the ArrayList class that we wrote during lecture. You may call the existing methods in ArrayList if you want, but do not use anything from the built-in java.util.ArrayList class. 1. (3 pts) Write a new method named addAll(ArrayList anotherList) that adds all the elements in anotherList to the back of the calling list. Be sure to reallocate the data array if necessary. anotherList should not be modified. 2. (4 pts) Write a new method named...

  • JAVA HELP (ARRAYS) Assignment Create a class named Module4 containing the following data members and methods...

    JAVA HELP (ARRAYS) Assignment Create a class named Module4 containing the following data members and methods (note that all data members and methods are for objects unless specified as being for the entire class) 1) Data members: none 2) Methods a. A method named displayContents that accepts an array of type int and prints their values to the b. A method named cemoveNegatives that accepts an array of type int, copies all its non-negative the new array should be the...

  • JAVA you have been given the code for Node Class (that holds Strings) and the LinkedList...

    JAVA you have been given the code for Node Class (that holds Strings) and the LinkedList Class (some methods included). Remember, you will use the LinkedList Class that we developed in class not Java’s LinkedList Class. You will add the following method to the LinkedList Class: printEvenNodes – this is a void method that prints Nodes that have even indices (e.g., 0, 2, 4, etc). Create a LinkedListDemo class. Use a Scanner Class to read in city names and store...

  • Your text has an example of LinkedList class. Convert the class so that the Link objects have a s...

    Your text has an example of LinkedList class. Convert the class so that the Link objects have a single long instance variable -- call it "data" -- and the Link instance variable.. Step 2 Then add the following capabilities to the class. A constructor that takes an array of longs as an argument. The contents of the array are use to create Link objects that become objects in the LinkedList. A "search" method that takes a long argument and returns...

  • Please use Java programming: Modify both ArrayList and LinkedList classes and add the following method to...

    Please use Java programming: Modify both ArrayList and LinkedList classes and add the following method to both classes: public void reverseThisList(), This method will reverse the lists. When testing the method: print out the original list, call the new method, then print out the list again ------------------------------------------------------------------------- //ARRAY LIST class: public class ArrayList<E> implements List<E> { /** Array of elements in this List. */ private E[] data; /** Number of elements currently in this List. */ private int size; /**...

  • java Create the following classes: DatabaseType: an interface that contains one method 1. Comparator getComparatorByTrait(String trait)...

    java Create the following classes: DatabaseType: an interface that contains one method 1. Comparator getComparatorByTrait(String trait) where Comparator is an interface in java.util. Database: a class that limits the types it can store to DatabaseTypes. The database will store the data in nodes, just like a linked list. The database will also let the user create an index for the database. An index is a sorted array (or in our case, a sorted ArrayList) of the data so that searches...

  • Programming in java In this part of this Lab exercise, you will need to create a...

    Programming in java In this part of this Lab exercise, you will need to create a new class named ArrayShiftMult. This class carries out simple manipulation of an array. Then you should add a main method to this class to check that your code does what it is supposed to do. 1. Create a BlueJ project named LAB06 as follows: a. Open the P drive and create a folder named Blue), if it does not exist already. Under this folder,...

  • Write a method public static ArrayList merge(ArrayList a, ArrayList b) that merges two array lists, alternating...

    Write a method public static ArrayList merge(ArrayList a, ArrayList b) that merges two array lists, alternating elements from both array lists. If one array list is shorter than the other, then alternate as long as you can and then append the remaining elements from the longer array list. For example, if a is 1 4 9 16 and b is 9 7 4 9 11 then merge returns the array list 1 9 4 7 9 4 16 9 11...

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
ADVERTISEMENT