Question

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 trimToSize() that changes the capacity of the calling list to the list’s current size. Example: If list1 is an ArrayList with 4 elements and a capacity of 7, calling list1.trimToSize() should change its capacity to 4.

3. (5 pts) Write a new method named slice(int beginIndex, int endIndex) that returns a new ArrayList object containing the elements of the calling list between beginIndex (inclusive) and endIndex (exclusive). The calling list should not be modified. This method should throw an IndexOutOfBoundsException if an invalid index is supplied, or if beginIndex is not at least 1 less than endIndex. Example: If list1 is an ArrayList object containing {1, 2, 3, 3, 6, 2, 2, 3, 1, 4}, then calling list1.slice(4,7) should return a new ArrayList object containing the values at indices 4, 5, and 6. The returned list would contain the elements {6, 2, 2}.

Add the following methods to the LinkedList class that we wrote during lecture (code posted on Oct. 25). You may call the existing methods in LinkedList if you want, but do not use anything from the built-in java.util.LinkedList class.

4. (3 pts) Write a new method named remove(E item) that removes and returns the first item in the list that is equivalent to the specified object. If the list does not contain such an item, the method should return null.

5. (6 pts) Write a new method named reverse() that reverses the order of the nodes in the calling list. (There are several ways you can do this, some of which are more efficient than others! As long as your solution works, it’s acceptable for this assignment. But if possible, try to make your solution run in O(n) time.)

6. (4 pts) Write a new method named toArrayList() that returns an ArrayList object containing all elements in the calling list, in the same order (i.e., the head node’s data should be stored in index 0 of the returned array list). Use your ArrayList class from the first part of this assignment. If the calling list is empty, just return an ArrayList of size 0.

#protips

As usual, be sure to test all of your methods thoroughly. When working with lists, you should always consider cases of performing an action on:

• An empty list • A list containing exactly one element • Something at the front of the list • Something at the back of the list • Something in the middle of the list

Please submit an answwer that follows all the given instructions. The last time this was tried, the answer given followed none of the instructions and was useless.

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

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class newArrayList extends ArrayList

{

private static final long serialVersionUID = 8683452581122892189L;

private transient Object[] elementData;

private int size;

public newArrayList(int initialCapacity) {

super();

if (initialCapacity < 0)

throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);

this.elementData = new Object[initialCapacity];

}

public newArrayList() {

this(10);

}

public newArrayList(Collection c) {

elementData = c.toArray();

size = elementData.length;

if (elementData.getClass() != Object[].class)

elementData = Arrays.copyOf(elementData, size, Object[].class);

}

public void trimToSize() {

int oldCapacity = elementData.length;

if (size < oldCapacity) {

elementData = Arrays.copyOf(elementData, size);

}

}

public boolean addAll(Collection c) {

Object[] a = c.toArray();

int numNew = a.length;

ensureCapacity(size + numNew); // Increments modCount

System.arraycopy(a, 0, elementData, size, numNew);

size += numNew;

return numNew != 0;

}

private void fastRemove(int index) {

int numMoved = size - index - 1;

if (numMoved > 0)

System.arraycopy(elementData, index+1, elementData, index, numMoved);

elementData[--size] = null; // Let gc do its work

}

public Object get(int index){
   return elementData[index];
}

public boolean remove(Object o) {

if (o == null) {

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

if (elementData[index] == null) {

fastRemove(index);

return true;

}

} else {

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

if (o.equals(elementData[index])) {

fastRemove(index);

return true;

}

}

return false;

}

public void reverse() {

int oldCapacity = elementData.length;

Object[] copyElementData = new Object[1000];

for (int index = size, i = 0; index >= 0 && i > size; index--, i++){

   copyElementData[index] = elementData[i];

}

elementData = copyElementData;

}

public static Collection toArrayList(Collection c){

newArrayList newElementData = new newArrayList(c);

return newElementData;

}

}

Add a comment
Know the answer?
Add Answer to:
Add the following methods to the ArrayList class that we wrote during lecture. You may call...
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
  • JAVA PROGRAMMING PLEASE This lab has three parts: Create an ArrayList class. Create a LinkedList class....

    JAVA PROGRAMMING PLEASE This lab has three parts: Create an ArrayList class. Create a LinkedList class. 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...

  • 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 Write a generic method that takes an ArrayList of objects (of a valid concrete object...

    java Write a generic method that takes an ArrayList of objects (of a valid concrete object type) and returns a new ArrayList containing no duplicate elements from the original ArrayList. The method signature is as follows: public static ArrayList UniqueObjects(ArrayList list) Test the method with at least 2 array lists of different concrete object types. Label your outputs properly and show the array lists content before and after calling method UniqueObjects

  • iii.print out the arraylist iv.reverse all the elements v.print out this arraylist vi.make a clone of...

    iii.print out the arraylist iv.reverse all the elements v.print out this arraylist vi.make a clone of the arraylist vii.remove all the elements at any odd index of the original arraylist (not the cloned one) viii.print out the original arraylist ix.reverse the cloned arraylist x.print out the cloned arraylist (this arraylist should still contain the original sequence of elements in order) xi.merge the cloned arraylist to the original arraylist (please think about what happens and draw a diagram for yourself to...

  • JAVA - Write a function in your Main class LinkedList<E> mergeLists(LinkedList<E> list1, LinkedList<E> list2) - given...

    JAVA - Write a function in your Main class LinkedList<E> mergeLists(LinkedList<E> list1, LinkedList<E> list2) - given two ordered linked lists of integers, merge the two lists into a single LinkedList whose elements are in sorted order. You should create a new LinkedList and add the values from list1 and list2 into the new list in sorted order. Do not modify list1 or list 2. list1 => 1 -> 3 -> 7 -> 8, list2 => 2 -> 5 -> 7...

  • if we have following List classes: public class LinkedList<T> { class ListNode { protected T value;...

    if we have following List classes: public class LinkedList<T> { class ListNode { protected T value; protected ListNode next; public ListNode(T val, ListNode nxt) { value = val; next = nxt; } public ListNode(T val) { this(val, null); } public ListNode() { this(null, null); } } can you write the folowing methods in java: 1.Write a method for the LinkedList class called int indexOf(T val) which returns the integer index indicating the location of val in the list, or -1...

  • JAVA (implementing a collection class) write a completed program (must include MAIN) and straight to the output based on 4. Based on the implementation of ArrayIntlist or ArrayList, write a class Sor...

    JAVA (implementing a collection class) write a completed program (must include MAIN) and straight to the output based on 4. Based on the implementation of ArrayIntlist or ArrayList, write a class SortedIntList or SortedList that provides most of the same operations but maintains its elements in sorted order. When a new value is added to the sorted list rather than appending it to the end of the list, it is placed in the appropriate index to maintain sorted order of...

  • 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 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...

  • In Java You may add any classes or methods to the following as you see fit in order to complete t...

    In Java You may add any classes or methods to the following as you see fit in order to complete the given tasks. Modify the LinkedList (or DoubleLinkedList) class and add a method append. append should take another LinkedList (DoubleLinkedList) as input and append that list to the end of this list. The append method should work by doing a few "arrow" adjustments on the boxes and it should not loop through the input list to add elements one at...

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