Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Objective The objective is to incorporate Java code you previously wrote and tes

ID: 3691711 • Letter: O

Question

Objective

The objective is to incorporate Java code you previously wrote and tested into a class that is being built.

What to do

You will add two methods to SimpleList: a constructor and an instance method.

public Object[] toArray()
This instance method will return an array with the contents of the list in order.

public SimpleList(Object[] array)
This constructor takes an array and initializes this list to contain the same elements in the same order. Be careful of the case when the list is empty. But, otherwise, this just uses the techniques you have been practicing.

Testing

Write a short program to create an array, create a SimpleList from that array and then create an array from the list. These steps should use the methods you created today. Make sure that you print the original array and the final array so that they can be compared. Also print out the SimpleList created to compare its content.

Continue testing by adding an element to the end of the SimpleList, convert the modified list to an array and print out the array. Also print out the modified SimpleList directly as well.

Finally, create an empty array:
Object[] arre = {};
create a SimpleList from that array and then convert the list back to an array. Print the length of the resulting array and make sure it is 0. The purpose of this part is to make sure that an empty array is handled properly.

The code I have previously written is here:

Node:
public class Node {
private Object data;
private Node link;

public Node(Object initData, Node initLink) {
data = initData;
link = initLink;
}

public Node(Object initData) {
data = initData;
}

public Node() {
}

public Object getData() {
return data;
}

public void setData(Object data) {
this.data = data;
}

public Node getLink() {
return link;
}

public void setLink(Node link) {
this.link = link;
}


}


Toolkit:
import java.util.Objects;

public class Toolkit {

public static int size(Node head) {
int count = 0;
while(head != null) {
count++;
head = head.getLink();
}
return count;
}


/**
* Insert a new node at the beginning of the list pointed to by head.
* Return the new beginning of the list, the new node.
* The new node will contain the data 'entry'.
*/
public static Node headInsert(Node head, Object entry){
Node newNode = new Node(entry, head);
return newNode;
}

/**
* Insert a new node after the node pointed to by previous.
* Return the new node.
* The new node will contain the data 'entry'
* @param previous Should not be null
*/
public static Node insert(Node previous, Object entry) {
Node newNode = new Node(entry, previous.getLink());
previous.setLink(newNode);
return newNode;
}

/**
* Search for target in the list pointed to by head and return the first node found.
* Return null if no node is found.
*/
public static Node search(Node head, Object target) {
Node cursor = head;
while(cursor != null && !cursor.getData().equals(target)) {
cursor = cursor.getLink();
}
return cursor;
}

/**
* Return the node at index 'n' in the list starting at head.
* If n is out of bounds, throw an index out of bounds exception.
*/
public static Node locate(Node head, int n) {
if(n < 0) {
throw new IndexOutOfBoundsException("Node list locate index out of bounds: " + n);
}
else {
int counter = 0;
Node cursor = head;
while(cursor != null && counter < n) {
cursor = cursor.getLink();
counter++;
}
if(cursor == null)
throw new IndexOutOfBoundsException("Node list locate index out of bounds: " + n);
else
return cursor;
}
}

/**
* Remove the head node of the list starting at head.
* Return the head of the new list.
*
* @param head Should not be null
*
*/
public static Node headRemove(Node head) {
return head.getLink();
}

/**
* Remove the node following node previous.
* Returns the new node next after previous.
*
* @param previous Should not be null. Also, the next node after should
* not be null.
*/
public static Node remove(Node previous) {
Node nextNode = previous.getLink();
Node theNext = nextNode.getLink();
previous.setLink(theNext);
return theNext;
}

/**
* Create a copy of the list start at head and return the starting node of the copy.
*/
public static Node copy(Node head) {
if(head == null)
return null;
else {
Node h = headInsert(null, head.getData());
Node t = h;
Node cursor = head.getLink();
while (cursor != null) {
t = insert(t, cursor.getData());
cursor = cursor.getLink();
}
return h;
}
}

}


SimpleList:
public class SimpleList {
private Node head;
// private Node tail;

public SimpleList() {
}

/**
* Return the element at index i.
* If i is out of bounds (less than 0 or greater than or
* equal to size()) throw an IndexOutOfBounds exception.
*/
public Object get(int i) {
return Toolkit.locate(head, i).getData();
}

/**
* Return the number of elements in the list.
*/
public int size() {
return Toolkit.size(head);
}

/**
* Change the value at index i to 'value'.
* Return the old value stored at index i.
* If i is out of bounds (less than 0 or greater than or
* equal to size()) throw an IndexOutOfBounds exception.
*
*/
public Object set(int i, Object value) {
Node n = Toolkit.locate(head,i);
Object rtval = n.getData();
n.setData(value);
return rtval;
}


/**
* Insert the new element so that it ends up as index 'index'.
* If i is out of bounds (less than 0 or greater than
* size()) throw an IndexOutOfBounds exception.
*
* Note that index is allowed to be equal to size(). This just
* means the new element will go at the end of the list.
*/
public void add(int index, Object element) {
if(head == null) {
head = Toolkit.headInsert(head, element);
// tail = head;
} else if(index == 0) {
head = Toolkit.headInsert(head, element);
// } else if(index == size()) {
// Toolkit.insert(tail, element);
} else {
Node p = Toolkit.locate(head, index-1);
Toolkit.insert(p, element);
}
}

/**
* Remove the element at index i and return the element value.
*
* If i is out of bounds (less than 0 or greater than or
* equal to size()) throw an IndexOutOfBounds exception.
*
* @param index
* @return
*/
public Object remove(int index) {
if(index < 0 || index >= size()) {
throw new IndexOutOfBoundsException("remove index out of bounds: " + index);
} else if(index == 0) {
Object rtval = head.getData();
head = Toolkit.headRemove(head);
// if(head == null || head.getLink()==null)
// tail = head;
return rtval;
} else {
Node n = Toolkit.locate(head, index-1);
Object rtval = n.getLink().getData();
Toolkit.remove(n);
return rtval;
}
}


@Override
public String toString() {
StringBuilder sb = new StringBuilder("[");
Node p = head;
while(p != null) {
sb.append(p.getData());
if(p.getLink() != null)
sb.append(",");
}
sb.append("]");
return sb.toString();
}

}

Explanation / Answer

TestNode.java

public class TestNode {

    public static void main(String[] args) {
        int size = 5;
        Node head = new Node(-56.2,
                    new Node(45.9,
                    new Node(-35.8,
                    new Node(14.7,
                    new Node(23.5)))));

        System.out.println("Third Element:   " + getElement(head,2));

        System.out.print("Printed List:    ");
        printList(head,size);

        double sum = 0;
        for (int i=0; i<size; ++i) {
            sum += (double) getElement(head,i);
//            System.out.println("Count: " + i);
        }
        System.out.println("Average:         " + sum/size);

        for(int i=0; i<size; ++i) {
            Node n = getNode(head,i);
            n.setData((double) n.getData() + 1);
        }
        System.out.print("Elements + 1:    ");
        printList(head,size);

        Node nHead = removeNode(head,1);
        System.out.print("W/o 2nd element: ");
        printList(nHead,findListSize(nHead));
    }

    public static Object getElement(Node head, int elem) {
        if(elem == 0) {
            return head.getData();
        }
        else {
            return getElement(head.getLink(),elem-1);
        }
    }
    public static Node getNode(Node head, int elem) {
        if(elem == 0) {
            return head;
        }
        else {
            return getNode(head.getLink(),elem-1);
        }
    }
    public static Node removeNode(Node head, int elem) {
        head = cloneList(head,findListSize(head));

        if(elem == 0) {
            return head.getLink();
        }
        else {
            Node prev = getNode(head, elem-1);
            Node next = getNode(head, elem+1);
            prev.setLink(next);

            return head;
        }
    }
    public static void printList(Node head, int length) {
        for (int i=0; i<length; ++i) {
            System.out.print(getElement(head,i) + " ");
        }
        System.out.println();
    }
    public static Node cloneList(Node head, int length) {
        if(length == 0) {
            if(head == null) {
                return null;
            }
            else {
                return new Node(head.getData());
            }
        }
        else {
            return new Node(head.getData(),cloneList(head.getLink(),length-1));
        }
    }
    public static int findListSize(Node head) {
        if (head.getLink() == null) {
            return 1;
        }
        else {
            return findListSize(head.getLink()) + 1;
        }
    }
}

Node.java
public class Node {
    private Object data;
    private Node link;

    public Node(Object initData, Node initLink) {
        data = initData;
        link = initLink;
    }

    public Node(Object initData) {
        data = initData;
    }

    public Node() {}

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public Node getLink() {
        return link;
    }

    public void setLink(Node link) {
        this.link = link;
    }


}

sample output

Third Element:   -35.8                                                                                                                                      
Printed List:    -56.2 45.9 -35.8 14.7 23.5                                                                                                                 
Average:         -1.5800000000000005                                                                                                                        
Elements + 1:    -55.2 46.9 -34.8 15.7 24.5                                                                                                                 
W/o 2nd element: -55.2 -34.8 15.7 24.5                                                                                                                      
                                                                                                                                                            
TestSimpleList.java
public class TestSimpleList {
    public static void main(String[] args) {
        forEachArr();
    }
    private static void manualAdd() {
        Node head = new Node(24);
        SimpleList list = new SimpleList();
        list.add(0,2);
        list.add(0,1);
        list.add(2,3);
        System.out.printf("Size_%d: %s ",list.size(),list.toString());
    }
    private static void arrayAdd() {
        System.out.println("First Part:");
        Object[] vals = {0,1,2,3,4};
        SimpleList list = new SimpleList(vals);
        Object[] listToArr = list.toArray();
        System.out.printf(
                "Array Elems: %s toStr Print: %s toArr Print: %s ",
                printArray(vals),
                list.toString(),
                printArray(listToArr));

        System.out.println(" Second Part:");
        list.append(5);
        listToArr = list.toArray();
        System.out.printf(
                "toStr Print: %s toArr Print: %s ",
                list.toString(),
                printArray(listToArr));

        System.out.println(" Third Part:");
        list.remove(0);
        listToArr = list.toArray();
        System.out.printf(
                "toStr Print: %s toArr Print: %s ",
                list.toString(),
                printArray(listToArr));
    }
    private static void emptyTest() {
        Object[] vals = {};
        SimpleList list = new SimpleList(vals);
        Object[] listToArr = list.toArray();
        System.out.printf(
                "Array Elems: %s toStr Print: %s toArr Print: %s ",
                printArray(vals),
                list.toString(),
                printArray(listToArr));
    }
    private static void forEachArr() {
        SimpleList list = new SimpleList(new Object[] {1,2,3});
        System.out.println(forEachPrint(list));
    }
    private static String printArray(Object[] arr) {
        StringBuilder sb = new StringBuilder("[");
        for(int i=0; i<arr.length; ++i) {
            sb.append(arr[i]);
            if(i < arr.length-1) {
                sb.append(",");
            }
        }

        sb.append("]");
        return sb.toString();
    }
    private static String forEachPrint(SimpleList list) {
        StringBuilder sb = new StringBuilder("[");
        for(Node n : list) {
            sb.append(n.getData());
            sb.append(" ");
        }
        sb.append("]");
        return sb.toString();
    }
}


SimpleList.java
import java.util.Iterator;

public class SimpleList implements Iterable<Node> {
    private class NodeIter implements Iterator {
        private Node current;

        public NodeIter(){
            reset();
        }

        public Node peek() {
            return current;
        }
        public Node next() {
            if(!hasNext()) {
                throw new NullPointerException("No next element");
            }
            else {
                Node ret = current;
                current = current.getLink();
                return ret;
            }
        }
        public boolean hasNext() {
            return (current != null);
        }
        public void point(Node n) {
            current = n;
        }
        public void reset() {
            current = head;
        }
    }

    private Node head;
    private NodeIter iter;

    public SimpleList(){
        iter = new NodeIter();
    }
    public SimpleList(Object[] items) {
        iter = new NodeIter();
        for(int i=0; i<items.length; ++i) {
            this.add(i,items[i]);
        }
    }
    public Iterator iterator() {
        return new NodeIter();
    }

    public int size() {
        iter.reset();
        if(head == null) {
            return 0;
        }
        else {
            int count = 0;
            do {
                ++count;
                iter.next().getData();
            } while(iter.hasNext());

            iter.reset();
            return count;
        }

//        return Toolkit.size(head);
    }
    public Object get(int i) {
        return Toolkit.locate(head, i).getData();
    }
    public Object set(int i, Object value) {
        Node n = Toolkit.locate(head,i);
        Object rtval = n.getData();
        n.setData(value);
        return rtval;
    }
    public void add(int index, Object element) {
        if(head == null || index == 0) {
            head = Toolkit.headInsert(head, element);
            iter.reset();
        }
        else {
            Node p = Toolkit.locate(head, index-1);
            Toolkit.insert(p, element);
        }
    }
    public void append(Object element) {
        add(size(),element);
    }
    public Object remove(int index) {
        if (index < 0 || index >= size()) {
            throw new IndexOutOfBoundsException("remove index out of bounds: " + index);
        } else if (index == 0) {
            Object rtval = head.getData();
            head = Toolkit.headRemove(head);
            iter.reset();
            return rtval;
        } else {
            Node n = Toolkit.locate(head, index - 1);
            Object rtval = n.getLink().getData();
            Toolkit.remove(n);
            return rtval;
        }
    }
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("[");
        Node p = head;
        while(p != null) {
            sb.append(p.getData());
            if(p.getLink() != null)
                sb.append(",");
            p = p.getLink();
        }
        sb.append("]");
        return sb.toString();
    }

    public Object[] toArray() {
        Object[] arr = new Object[size()];
        int index = 0;
        while(iter.hasNext()) {
            arr[index] = iter.next().getData();
            ++index;
        }

        return arr;
    }

}


Node.java
public class Node {
    private Object data;
    private Node link;

    public Node(Object initData, Node initLink) {
        data = initData;
        link = initLink;
    }

    public Node(Object initData) {
        data = initData;
    }

    public Node() {}

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public Node getLink() {
        return link;
    }

    public void setLink(Node link) {
        this.link = link;
    }


}

Toolkit.java
import java.util.Objects;

public class Toolkit {

    public static int size(Node head) {
        int count = 0;
        while(head != null) {
            count++;
            head = head.getLink();
        }
        return count;
    }


    /**
     * Insert a new node at the beginning of the list pointed to by head.
     * Return the new beginning of the list, the new node.
     * The new node will contain the data 'entry'.
     */
    public static Node headInsert(Node head, Object entry){
        Node newNode = new Node(entry, head);
        return newNode;
    }

    /**
     * Insert a new node after the node pointed to by previous.
     * Return the new node.
     * The new node will contain the data 'entry'
     * @param previous Should not be null
     */
    public static Node insert(Node previous, Object entry) {
        Node newNode = new Node(entry, previous.getLink());
        previous.setLink(newNode);
        return newNode;
    }
    /**
     * Remove the head node of the list starting at head.
     * Return the head of the new list.
     *
     * @param head Should not be null
     *
     */
    public static Node headRemove(Node head) {
        return head.getLink();
    }

    /**
     * Remove the node following node previous.
     * Returns the new node next after previous.
     *
     * @param previous Should not be null. Also, the next node after should
     *                  not be null.
     */

    public static Node remove(Node previous) {
        Node nextNode = previous.getLink();
        Node theNext = nextNode.getLink();
        previous.setLink(theNext);
        //previous.setLink(previous.getLink().getLink());
        return theNext;
    }
    /**
     * Search for target in the list pointed to by head and return the first node found.
     * Return null if no node is found.
     */
    public static Node search(Node head, Object target) {
        Node cursor = head;
        while(cursor != null && !cursor.getData().equals(target)) {
            cursor = cursor.getLink();
        }
        return cursor;
    }

    /**
     *   Return the node at index 'n' in the list starting at head.
     *   If n is out of bounds, throw an index out of bounds exception.
     */
    public static Node locate(Node head, int n) {
        if(n < 0) {
            throw new IndexOutOfBoundsException("Node list locate index out of bounds: " + n);
        }
        else {
            int counter = 0;
            Node cursor = head;
            while(cursor != null && counter < n) {
                cursor = cursor.getLink();
                counter++;
            }
            if(cursor == null)
                throw new IndexOutOfBoundsException("Node list locate index out of bounds: " + n);
            else
                return cursor;
        }
    }
    /**
     * Create a copy of the list start at head and return the starting node of the copy.
     */
    public static Node copy(Node head) {
        if(head == null)
            return null;
        else {
            Node h = headInsert(null, head.getData());
            Node t = h;
            Node cursor = head.getLink();
            while (cursor != null) {
                t = insert(t, cursor.getData());
                cursor = cursor.getLink();
            }
            return h;
        }
    }

}

output
[123]


TestToolkit.java
public class TestToolkit {
    public static void main(String[] args) {
//        Create list with values -56.2 45.9 -35.8 14.7 23.5
        Node head = Toolkit.headInsert(null,23.5);
        head = Toolkit.headInsert(head,14.7);
        head = Toolkit.headInsert(head,-35.8);
        head = Toolkit.headInsert(head,45.9);
        head = Toolkit.headInsert(head,-56.2);
        int size = Toolkit.size(head);

//        Print element three's data
        System.out.println("Third Element: " + Toolkit.locate(head,2).getData());

//        Print the list
        System.out.print("List: ");
        printList(head,size);

//        Add the elements in list and average it
        double sum=0;
        for(int i=0; i<size; ++i) {
            sum += (double) Toolkit.locate(head,i).getData();
            System.out.println("Count: " + i);
        }
        System.out.println("Average: " + sum/5);

//        Add 1 to each element in list
        for(int i=0; i<size; ++i) {
            Node n = Toolkit.locate(head,i);
            n.setData((double) n.getData() + 1);
        }
        System.out.print("List: ");
        printList(head,size);

//        Append new values to list
        double[] newVals = {98.6, -73.2, 85.1, -64.3};
        for(double d : newVals) {
            Toolkit.insert(getLast(head),d);
        }
        size = Toolkit.size(head);
        System.out.print("List: ");
        printList(head,size);

//        Find element of value 24.5 and remove element after it
        Toolkit.remove(Toolkit.search(head,24.5));
        size = Toolkit.size(head);
        System.out.print("List: ");
        printList(head,size);

//        Print value of element at 5th index
        System.out.println("Index 5 Data: " + Toolkit.locate(head,5).getData());

//        Insert new value after the sixth index
        Toolkit.insert(Toolkit.locate(head,6),111.222);
        size = Toolkit.size(head);
        System.out.print("List: ");
        printList(head,size);

//        Remove the second element
        Toolkit.remove(head);
        size = Toolkit.size(head);
        System.out.print("List: ");
        printList(head,size);
    }

    private static void printList(Node head, int size) {
        for (int i=0; i<size; ++i) {
            System.out.print(Toolkit.locate(head,i).getData() + " ");
        }
        System.out.println();

    }
    private static Node getLast(Node head) {
        return Toolkit.locate(head, Toolkit.size(head)-1);
    }
}


sample output

Third Element: -35.8                                                                                                                                        
List: -56.2 45.9 -35.8 14.7 23.5                                                                                                                            
Count: 0                                                                                                                                                    
Count: 1                                                                                                                                                    
Count: 2                                                                                                                                                    
Count: 3                                                                                                                                                    
Count: 4                                                                                                                                                    
Average: -1.5800000000000005                                                                                                                                
List: -55.2 46.9 -34.8 15.7 24.5                                                                                                                            
List: -55.2 46.9 -34.8 15.7 24.5 98.6 -73.2 85.1 -64.3                                                                                                      
List: -55.2 46.9 -34.8 15.7 24.5 -73.2 85.1 -64.3                                                                                                           
Index 5 Data: -73.2                                                                                                                                         
List: -55.2 46.9 -34.8 15.7 24.5 -73.2 85.1 111.222 -64.3                                                                                                   
List: -55.2 -34.8 15.7 24.5 -73.2 85.1 111.222 -64.3