Question

In: Computer Science

. Implement your own custom linked list array implementation with the following changes: (a) Fill in...

. Implement your own custom linked list array implementation with the following changes:
(a) Fill in the public E get(int index) method
(b) Also add code to the get method to print out a message for each time an element in the list is
checked while searching for the element
You may want to study how the toString method goes from element to element in the list

Java

Solutions

Expert Solution

import java.util.Iterator;

import java.util.NoSuchElementException;


public class ArrayList<E> {

        // instance variables

        /** Default array capacity. */
        public static final int CAPACITY = 16; // default array capacity

        /** Generic array used for storage of list elements. */
        private E[] data; // generic array used for storage

        /** Current number of elements in the list. */
        private int size = 0; // current number of elements

        // constructors

        /** Creates an array list with default initial capacity. */
        public ArrayList() {
                this(CAPACITY);
        } // constructs list with default capacity

        /** Creates an array list with given initial capacity. */
        @SuppressWarnings({ "unchecked" })
        public ArrayList(int capacity) { // constructs list with given capacity
                data = (E[]) new Object[capacity]; // safe cast; compiler may give
                                                                                        // warning
        }
        
        public void addAll(ArrayList<E> l){
                int listSize = l.size();
                for(int i=0; i<listSize; i++) {
                        add(size(), l.get(i));
                }
        }
        
        public boolean remove(E element) {
                int listSize = size();
                int index = -1;
                for(int i=0; i<listSize; i++) {
                        if(get(i).equals(element)) {
                                index = i;
                                break;
                        }
                }
                
                if(index != -1) {
                        remove(index);
                        return true;
                } else {
                        return false;
                }               
        }
        
        public boolean search(E element) {
                for(int i=0; i<size; i++) {
                        System.out.println("Checking " + data[i]);
                        if(data[i].equals(element)) {
                                return true;
                        }
                }
                
                return false;
        }
        
        public void removeRange(int fromIndex, int toIndex){
                for(int i=toIndex - 1; i >= fromIndex; i--) {
                        if((i >= 0) && (i < size)) {
                                remove(i);
                        }
                }
        }
        
        public void trimToSize() {
                resize(size);           
        }

        // public methods
        public int size() {
                return size;
        }

        public boolean isEmpty() {
                return size == 0;
        }

        public E get(int i) throws IndexOutOfBoundsException {
                checkIndex(i, size);
                return data[i];
        }

        public E set(int i, E e) throws IndexOutOfBoundsException {
                checkIndex(i, size);
                E temp = data[i];
                data[i] = e;
                return temp;
        }

        /**
         * 
         * Inserts the given element at the specified index of the list, shifting
         * all
         * 
         * subsequent elements in the list one position further to make room.
         * 
         * @param i
         *            the index at which the new element should be stored
         * 
         * @param e
         *            the new element to be stored
         * 
         * @throws IndexOutOfBoundsException
         *             if the index is negative or greater than size()
         */
        public void add(int i, E e) throws IndexOutOfBoundsException {
                checkIndex(i, size + 1);

                if (size == data.length) // not enough capacity
                        resize(2 * data.length); // so double the current capacity

                for (int k = size - 1; k >= i; k--)
                        // start by shifting rightmost

                        data[k + 1] = data[k];

                data[i] = e; // ready to place the new element

                size++;

        }

        /**
         * 
         * Removes and returns the element at the given index, shifting all
         * subsequent
         * 
         * elements in the list one position closer to the front.
         * 
         * @param i
         *            the index of the element to be removed
         * 
         * @return the element that had be stored at the given index
         * 
         * @throws IndexOutOfBoundsException
         *             if the index is negative or greater than size()
         */
        public E remove(int i) throws IndexOutOfBoundsException {

                checkIndex(i, size);

                E temp = data[i];

                for (int k = i; k < size - 1; k++)
                        // shift elements to fill hole
                        data[k] = data[k + 1];

                data[size - 1] = null; // help garbage collection

                size--;

                return temp;

        }

        // utility methods
        /** Checks whether the given index is in the range [0, n-1]. */
        protected void checkIndex(int i, int n) throws IndexOutOfBoundsException {

                if (i < 0 || i >= n)
                        throw new IndexOutOfBoundsException("Illegal index: " + i);

        }

        /** Resizes internal array to have given capacity >= size. */

        @SuppressWarnings({ "unchecked" })
        protected void resize(int capacity) {
                E[] temp = (E[]) new Object[capacity]; // safe cast; compiler may give
                                                                                                // warning
                for (int k = 0; k < size; k++)
                        temp[k] = data[k];

                data = temp; // start using the new array
        }

        /**
         * 
         * Produces a string representation of the contents of the indexed list.
         * This exists for debugging purposes only.
         * 
         * @return textual representation of the array list
         */
        public String toString() {
                StringBuilder sb = new StringBuilder("(");
                for (int j = 0; j < size; j++) {
                        if (j > 0)
                                sb.append(", ");
                        sb.append(data[j]);
                }

                sb.append(")");
                return sb.toString();
        }

        public void printList() {
                System.out.println();
                for (int i = 0; i < size; i++) {
                        System.out.print(get(i) + " ");
                }

                System.out.println();
        }

        public static void main(String[] args) {

                ArrayList<String> stringList1 = new ArrayList<>(3);
                stringList1.add(0, "Java");
                stringList1.add(0, "with");
                stringList1.add(0, "Structure");
                stringList1.add(0, "Data");
                stringList1.printList();
                
                stringList1.remove(2);
                stringList1.printList();

                stringList1.set(2, "Python");
                stringList1.printList();

                ArrayList<String> stringList2 = new ArrayList<>(3);
                stringList2.add(0, "using");
                stringList2.add(1, "Collections");
                stringList2.printList();
                
                stringList1.addAll(stringList2);
                stringList1.printList();
                
                stringList1.remove("Python");
                stringList1.printList();
                
                stringList1.removeRange(1, 3);
                stringList1.printList();
                
                stringList1.trimToSize();
                stringList1.printList();
        }

}





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

Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.

Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.


Related Solutions

1. Adapt the custom array list implementation code with the following changes: (a) Add code to...
1. Adapt the custom array list implementation code with the following changes: (a) Add code to the ensureCapacity() method to print out a message including how many elements are copied to the new array on resizing Array List Implementation: public class MyArrayList<E> implements MyList<E> { public static final int INITIAL_CAPACITY = 16; private E[] data = (E[])new Object[INITIAL_CAPACITY]; private int size = 0; // Number of elements in the list public MyArrayList() { }    public MyArrayList(E[] objects) { for...
C++ question: Design and implement your own linked list class to hold a sorted list of...
C++ question: Design and implement your own linked list class to hold a sorted list of integers in ascending order. The class should have member functions for inserting an item in the list, deleting an item from the list, and searching the list for an item. Note: the search function should return the position of the item in the list (first item at position 0) and -1 if not found. In addition, it should have member functions to display the...
IN JAVA LANGUAGE Linked List-Based Queue Implementation Implement Queue using a Linked List. Use the language...
IN JAVA LANGUAGE Linked List-Based Queue Implementation Implement Queue using a Linked List. Use the language library LinkedList Queue methods will call the LinkedList methods You can use string as the object Instead of using an array, as the QueueLab did, here you will use a Linked List from your language's library. Implement all the methods of Stack : enqueue(), dequeue(), size(), printQueue(), etc, using calls to the linked list methods that correspond to the actions need. In the array...
IN JAVA LANGUAGE Linked List-Based Stack Implementation Implement Stack using a Linked List Use the language...
IN JAVA LANGUAGE Linked List-Based Stack Implementation Implement Stack using a Linked List Use the language library LinkedList Stack methods will call the LinkedList methods You can use string as the object Instead of using an array, as the StackLab did, here you will use a Linked List from your language's library. Implement all the methods of Stack : push(), pop(), size(), printStackDown(), etc, using calls to the linked list methods that correspond to the actions need. In the array...
In this Java program you will implement your own doubly linked lists. Implement the following operations...
In this Java program you will implement your own doubly linked lists. Implement the following operations that Java7 LinkedLists have. 1. public DList() This creates the empty list 2. public void addFirst(String element) adds the element to the front of the list 3. public void addLast(String element) adds the element to the end of the list 4. public String getFirst() 5. public String getLast() 6. public String removeLast() removes & returns the last element of the list. 7. public String...
Make following changes. step(A) step 1 Implementation a Generic Linked List using the program developed in...
Make following changes. step(A) step 1 Implementation a Generic Linked List using the program developed in the class. step 2  Implement StackImpl class using the generic linked list. step 3 Test the program with different type and number of matching and un-matching brackets. This is how it works! When you run the class MatchBrackets a popup dialog appears asking you to select a file. You are provided two input files in the project. input1.txt contains matching brackets and input2.txt does not...
Linked List: Complete the following code to create a linked list from an Array. After creating...
Linked List: Complete the following code to create a linked list from an Array. After creating the list, display the elements of the linked list iteratively. Write two others function called as RDisplayTailRecursion(first) and RDisplayTailRecursion(first) which will print elements of the linked list using the tail and head recursions respectively. #include <stdio.h> #include <stdlib.h> struct Node { }*first=NULL; void create(int A[], int n) { for(i=1; i<n; i++) { } } void Display(struct Node*p) { while(p!=NULL) { } } void RDisplayTailRecursion...
Could you check/edit my code? Design and implement your own linked list class to hold a...
Could you check/edit my code? Design and implement your own linked list class to hold a sorted list of integers in ascending order. The class should have member function for inserting an item in the list, deleting an item from the list, and searching the list for an item. Note: the search function should return the position of the item in the list (first item at position 0) and -1 if not found. In addition, it should member functions to...
Data structure program Implement (your own) the Radix Sort using single linked list java language
Data structure program Implement (your own) the Radix Sort using single linked list java language
Array-Based Linked List Implementation: JAVA Decide how to write the methods with items being stored in...
Array-Based Linked List Implementation: JAVA Decide how to write the methods with items being stored in an array. NOT in linked List. Implement an array-based Linked List in your language. Use double as the item. You need to create a driver includes several items and inserts them in order in a list. Identify the necessary methods in a List Linked implementation. Look at previous Data Structures (stack or queue) and be sure to include all necessary methods. DO NOT USE...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT