How can I create a queue only given the implemented methods? - java

I have a class MyList with the following methods :
public class MyList{
ArrayList<Object> list;
MyList(int a, int b)
{
list = new ArrayList<Object>();
for(;a<=b;a++)
list.add(a);
}
public void add(int index, Object o)
{
list.add(index, o);
}
public Object remove(int index) throws isEmptyException
{
if(isEmpty())
throw new isEmptyException();
else
return list.remove(index);
}
public boolean isEmpty()
{
return list.isEmpty();
}
Here's my Class Queue. I have to implement the following methods using only the above methods from MyList.
public class Queue extends MyList{
public void enqueue(Object o)
{
//adds a new Object to the queue
}
public Object dequeue()
{
//removes the next Object from the queue and returns it
}
public boolean empty()
{
//Checks if the queue is empty
}
I don't really know where to start here, since I don't know the size of the queue. Can someone give me a hint how to solve this? Is a recursive method useful here?
Thanks in advance!

Call the add or remove inside the enqueue and dequeue methods of the Queue class, maintain a pointer to first and last.
public class Queue extends MyList {
private int index;
private int firstIndex;
Queue(int a, int b)
{
super(a, b);
}
public void enqueue(Object o)
{
add(o);
index++;
}
public Object deueue() throws Exception {
if(firstIndex == index || isEmpty()) {
firstIndex =0; index =0;
throw new Exception("");
}
else
return list.remove(++firstIndex);
}
public boolean isEmpty()
{
return list.isEmpty();
}
}

Related

How to write `getMin()` method for a linked stack class that extends Comparable? (Homework)

For this assignment I need to create a linked stack class that contains a getMin() and getMax(). I cannot change the class header which was provided by the instructor. Both getMin and getMax should be O(1) time.
My thought is that I need to use the compareTo method to compare entries as they are pushed or poped so that I can set variables minValue and maxValue equal to their respective values. However, I don't understand the section in the class header <T extends Comparable<? super T>> nor do I know how or where to implement Comparable. I tried having my class Node<E> implement Comparable but it asked me to override the compareTo method and I'm not sure how that would work.
Any help would be greatly appreciated! Below is my code for this assignment:
public class MinMaxStack <T extends Comparable<? super T>> implements StackADT<T> {
private Node<T> top;
private int size;
public MinMaxStack() {
clear();
}
private class Node<E>{
E data;
Node<E> previous;
}
public T getMin() {
if(isEmpty()) {
throw new EmptyCollectionException("The stack is empty but is trying to getMin.");
} else {
return null;
}
}
public T getMax() {
return null;
}
#Override
public T pop() {
if(isEmpty()) {
throw new EmptyStackException("Stack is empty but trying to pop.");
}else {
T dataToReturn = top.data;
top = top.previous;
size -= 1;
return dataToReturn;
}
}
#Override
public T peek() {
if(isEmpty()) {
throw new EmptyStackException("Stack is empty but trying to peek");
}else {
return top.data;
}
}
#Override
public void push(T newItem) {
Node<T> newNode = new Node<>();
newNode.data = newItem;
if(!isEmpty()) {
newNode.previous = top;
}
top = newNode;
size += 1;
}
#Override
public int getSize() {
return size;
}
#Override
public void clear() {
while(!isEmpty()) {
top = null;
size = 0;
}
}
#Override
public boolean isEmpty() {
return size == 0;
}
}

Compiler asking for optional methods from Collections to be overridden

I'm creating a class-wide project with my school mates, I'm supposed to create pull requests for some functions, but I'm having some problems just creating the class and overriding the methods in a way that it would just compile (I don't need to write the methods at this moment, that's the project, I just need it to compile). I've found most methods are working (or at least the compiler is not complaining), but I'm confused about a few things:
Compiler complaining about methods that are optional (like set, and addAll)
The method addAll, although it was added, complains that it wasn't overridden, although it was, and when I add the other addAll method for it, then I get an erasure error as well.
I've read a bunch about it, but I couldn't find a proper conclusion on how to solve it. I'm just using Atom to write my code, and the Terminal, no fancy IDE (perhaps I should learn one).
In case it isn't clear, I'm just looking to have the stubs of the methods available, not an all around answer for every single method, since this is the project with the class.
// https://docs.oracle.com/javase/8/docs/api/java/util/List.html
import java.util.*;
import java.lang.reflect.*;
public class SkipList<E> implements List<E>
{
// compiler complaining, then added, although optional
public E set(int index, E element)
{
throw new IndexOutOfBoundsException();
}
// compiler complaining, then added, although optional
public boolean addAll(Collection <? extends E> c)
{
return true;
}
// Group 1
public boolean add(E e)
{
return true;
}
public void add(int index, E e)
{
}
public boolean addAll(Collection c)
{
return true;
}
public int indexOf(Object o)
{
int index = 0;
return index;
}
public int lastIndexOf(Object o)
{
int index = 0;
return index;
}
// Group 2
public boolean contains(Object o)
{
return true;
}
public boolean containsAll(Collection c)
{
return true;
}
public boolean equals(Object o)
{
return true;
}
public List<E> subList(int fromIndex, int toIndex)
{
List<E> sub = new SkipList<>();
return sub;
}
// Group 3
public boolean isEmpty()
{
return true;
}
public int size()
{
int size = 0;
return size;
}
public void clear()
{
}
public E get(int index)
{
throw new IndexOutOfBoundsException();
}
public E getQuantile(double quantile) // e.g. 0 = minimum, 0.5 = median, 1 = max
{
throw new IndexOutOfBoundsException();
}
// Group 4
public Iterator<E> iterator()
{
throw new IndexOutOfBoundsException();
}
public ListIterator<E> listIterator()
{
throw new IndexOutOfBoundsException();
}
public ListIterator<E> listIterator(int index)
{
throw new IndexOutOfBoundsException();
}
// Group 5
public E remove(int index)
{
throw new IndexOutOfBoundsException();
}
public boolean remove(Object o)
{
return true;
}
public boolean removeAll(Collection c)
{
return true;
}
public boolean retainAll(Collection c)
{
return true;
}
// Group 6
public int hashCode()
{
int hashCode = 0;
return hashCode;
}
public Object[] toArray()
{
Object[] arr = new Object[0];
return arr;
}
public <T> T[] toArray(T[] a)
{
return a;
}
}
Turns out that when reading the API, for some reason I glossed over the other parameter for the addAll method, that led me to believe something else was wrong. I changed the method with the correct parameters and it compiled.
public boolean addAll(int index, Collection <? extends E> c)
{
return true;
}

how to realize a queue in java?

I want to do the same thing I did in this code for stack
how can i change it so it will be for queue? I don't want to use stack or LinkedList for that
public StackAsArray(){
this(new DynamicArray());
}
public boolean isEmpty() {
}
public void push(Object o) {
}
public Object pop() {
}
}
You just need to replace your push and pop methods with enqueue and dequeue methods.
enqueue adds elements to the end of the array, while dequeue will remove it from the beginning.
public class QueueAsArray implements Queue {
...
public void enqueue(Object o) {
arr.set(numOfElements, o);
numOfElements++;
}
public Object dequeue() {
if(isEmpty()) { // an empty check is a MUST
return null;
}
numOfElements = numOfElements - 1;
Object res = arr.get(0);
arr.set(0, null); // not 100% sure this works, but since this is a homework question, its upto you to figure out. The logic is to remove the 0th element.
return res;
}
}

Java: queue isn't displaying all records

I am trying to add patient records into a queue and then display all the records on the screen but I am not getting them.. I guess the display method isn't working for me.. I probably made a mistake.. Here is my code for queue of the patients.
public class Patient_Queue {
private LinkedList list;
public Patient_Queue()
{
// Create a new LinkedList.
list= new LinkedList();
}
public boolean isEmpty()
{
return (list.size() == 0);
}
public void joinQueue(Object item)
{
list.add(item);
}
public Object Consultation()
{
Object item = list;
list.remove(0);
return item;
}
public void display() {
for(int q=0;q<list.size();q++)
{
System.out.println(list.get(q));
}
}
public int size(){
return list.size();
}
public void clear()
{
list.clear();
}
}
It seems to be a mistake here:
public Object Consultation()
{
Object item = list;
list.remove(0);
return item;
}
Corrected version:
public Object Consultation()
{
Object item = list.get(0); // fix
list.remove(0);
return item;
}
Note that LinkedList implements Queue interface and you can use its Queue methods directly.

Exception in thread "main" java.lang.ArrayStoreException when store object into array

This is my whole code, the problem requires me to use Array for solution.
import java.lang.reflect.Array;
public class MyStack<T> {
public MyStack (Class<T[]> _class,int size){
final T[] values = (T[]) Array.newInstance(_class,size);
this.values = values;
this.size=size;
}
private T[] values;
private int top=0,size;
public void push(T nextElement){
if(isFull()){
System.out.println("full");
}
else {
values[top++] = nextElement;
}
}
public T pop(){
if(isEmpty()) {
System.out.println("empty");
return null;
}
else {
return values[top--];
}
}
public boolean isEmpty(){
if (top==0)return true;
return false;
}
public boolean isFull(){
if(top==size-1)return true;
else return false;
}
public static void main(String args[]){
MyStack<Integer> myStack = new MyStack<Integer>(Integer[].class,9);
for (int i =0;i<10;i++)
{
myStack.push(i);
}
while(!myStack.isEmpty()){
System.out.println(myStack.pop());
}
}
}
When i compile it it throws Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer at values[top++] = nextElement; no matter which type i used from String, Integer or any other Objects.
Is there a way to fix this problem ?
You constructor takes a Class<T[]> but should take a Class<T>, also you don't need a variable shadow on values. I'd write it like
public MyStack(Class<T> _class, int size) {
this.values = (T[]) Array.newInstance(_class, size);
this.size = size;
}
You don't need if else chains for isEmpty (just return the condition you are testing directly) - like
public boolean isEmpty() {
return top == 0;
}
Or for isFull
public boolean isFull() {
return top == size - 1;
}

Categories

Resources