The assignment reads:
Give a complete implementation of a priority queue using an array of ordinary queues. For your ordinary queue, use the version...on page 402.
Pg402 reads:
public class PriorityQueue<E>
{
private ArrayQueue<E>[] queues;
...
In this implementation, the constructor allocates the memory for the array of queues with the statement:
queues = (ArrayQueue<E>[]) new Object[highest+1];
However:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Lpriorityqueue.Queue;
at priorityqueue.PriorityQueue.(PriorityQueue.java:17)
at priorityqueue.PriorityQueue.main(PriorityQueue.java:67)
Java Result: 1
Exception on data = (Queue<T>[]) new Object[highPriority];
public class PriorityQueue<T>
{
private Queue<T>[] data;
private int size, hprior;
#SuppressWarnings("unchecked")
public PriorityQueue(int highPriority)
{
if(highPriority < 1)
throw new RuntimeException("Invalid priority number!");
data = (Queue<T>[]) new Object[highPriority]; //Error line 17
for(int i = 0; i < highPriority; i++)
{
data[i] = new Queue<>();
}
size = 0;
}
public void add(int priority, T element)
{
if(priority > data.length)
throw new RuntimeException("Invalid priority number!");
data[priority-1].enqueue(element);
size++;
}
public T remove()
{
if(empty())
throw new RuntimeException("Priority Queue is Empty!");
T element = null;
for(int i = data.length; i < 0; i--)
{
if(data[i].size()!=0)
element = (T) data[i].dequeue();
break;
}
return element;
}
public int size()
{
return size;
}
public boolean empty()
{
return size == 0;
}
public static void main(String[] args)
{
PriorityQueue<String> pq = new PriorityQueue<>(10); //Error at line 67
pq.add(1, "hi");
pq.add(2, "there!");
System.out.println(pq.remove());
}
}
class Queue<T>
{
private int front, rear, size;
public final static int DEFAULT_CAPACITY = 64;
private T[] queue;
public Queue(int capacity)
{
queue = (T[]) new Object[capacity];
size = 0;
front = 0;
rear = 0;
}
public Queue()
{
this(DEFAULT_CAPACITY);
}
public void enqueue(T element)
{
if(size() == queue.length)
throw new RuntimeException("Queue Full!");
queue[rear]= element;
rear = (rear +1) % queue.length;
size++;
}
public T dequeue()
{
if(empty())
throw new RuntimeException("Queue empty!");
T element = queue[front];
front = (front +1) % queue.length;
size--;
return element;
}
public int size()
{
return size;
}
public T front()
{
return queue[front];
}
public boolean empty()
{
return size == 0;
}
}
You can't randomly cast Object to some other type. If you want a Queue<T>[], you need to actually construct one. You can't really create an array with generics, so you're going to have to do something like this:
Queue<T>[] queue = (Queue<T> []) new ArrayDeque[10]; //or whatever concrete implementation you want.
Related
interface Iterator {
boolean hasnext();
int next();
}
class practice5 {
public static void main(String a[]) {
Stack s = new Stack();
Queue q = new Queue();
Linkedlist l = new Linkedlist();
s.push(100);
s.push(200);
q.Enque(300);
q.Enque(400);
l.add(500);
l.add(600);
Iterator itr;
itr = s;
while (!itr.hasnext()) {
System.out.println(itr.next());
}
itr = q;
while (!itr.hasnext()) {
System.out.println(itr.next());
}
itr = l;
while (itr.hasnext()) {
System.out.println(itr.next());
}
}
}
class Stack extends Iterator {
private int stack[];
private int top;
public Stack() {
stack = new int[10];
top = -1;
}
public void push(int val) {
top++;
stack[top] = val;
}
public boolean hasnext() {
if (top >= 0) {
return false;
} else {
return true;
}
}
public int next() {
return (stack[top--]);
}
}
class Queue extends Iterator {
private int queue[];
private int front, rear;
public Queue() {
queue = new int[10];
front = 0;
rear = 0;
}
public void Enque(int val) {
queue[rear] = val;
rear++;
}
public boolean hasnext() {
if (front < rear) {
return false;
} else {
return true;
}
}
public int next() {
return (queue[front++]);
}
}
class Linkedlist extends Iterator {
private int data;
private Linkedlist nw, next, prev, first, guest;
public Linkedlist() {
nw = next = prev = first = null;
}
public void add(int val) {
nw = new Linkedlist();
nw.data = val;
if (first == null) {
prev = first = nw;
} else {
prev.next = nw;
prev = nw;
}
}
public boolean hasnext() {
if (guest != 0) {
return true;
} else {
return false;
}
}
public int next() {
int curval;
curval = first.data;
first = first.next;
return (curval);
}
}
I'm expecting that I get an output for the above code.
I need to know if I'm extending the Stack, Queue and LinkedList classes wrongly with the interface class. Whenever I'm pass the iterator class object the instance of my child class objects, I am getting an error.
Also, in the LinkedList section when I call guest != 0, I'm getting an error Bad Operand. How can I check and print whether my guest is equal to zero or not?
I'm trying to implement a generic stack.
Here's the interface
package stack;
public interface Stack<T>{
void push(T number);
T pop();
T peek();
boolean isEmpty();
boolean isFull();
}
Here's the class
package stack;
import java.lang.reflect.Array;
import java.util.EmptyStackException;
public class StackArray <T> implements Stack<T>{
private int maxSize;
private T[] array;
private int top;
public StackArray(int maxSize) {
this.maxSize = maxSize;
// #SuppressWarnings("unchecked")
this.array = (T[]) Array.newInstance(StackArray.class, maxSize);
this.top = -1;
}
private T[] resizeArray() {
/**
* create a new array double the size of the old, copy the old elements then return the new array */
int newSize = maxSize * 2;
T[] newArray = (T[]) Array.newInstance(StackArray.class, newSize);
for(int i = 0; i < maxSize; i++) {
newArray[i] = this.array[i];
}
return newArray;
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == maxSize-1;
}
public void push(T element) {
if(!this.isFull()) {
++top;
array[top] = element;
}
else {
this.array = resizeArray();
array[++top] = element;
}
}
public T pop() {
if(!this.isEmpty())
return array[top--];
else {
throw new EmptyStackException();
}
}
public T peek() {
return array[top];
}
}
Here's the Main class
package stack;
public class Main {
public static void main(String[] args) {
String word = "Hello World!";
Stack <Character>stack = new StackArray<>(word.length());
// for(Character ch : word.toCharArray()) {
// stack.push(ch);
// }
for(int i = 0; i < word.length(); i++) {
stack.push(word.toCharArray()[i]);
}
String reversedWord = "";
while(!stack.isEmpty()) {
char ch = (char) stack.pop();
reversedWord += ch;
}
System.out.println(reversedWord);
}
}
The error is
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Character
at stack.StackArray.push(StackArray.java:40)
at stack.Main.main(Main.java:14)
line 40 is in the push method
array[top] = element;
Side Question:
Any way to suppress the warning in the constructor? :)
The underlying issue is type erasure. The relevant implications of this means that an instance of the Stack class doesn't know it's type arguments at run-time. This is the reason why you can't just use the most natural solution here, array = new T[maxSize].
You've tried to work around this by creating an array using Array.newInstance(...), but unfortunately this array does not have elements of type T either. In the code shown the elements are of type StackArray, which is probably not what you intended.
One common way of dealing with this is to use an array of Object internally to Stack, and cast any return values to type T in accessor methods.
class StackArray<T> implements Stack<T> {
private int maxSize;
private Object[] array;
private int top;
public StackArray(int maxSize) {
this.maxSize = maxSize;
this.array = new Object[maxSize];
this.top = -1;
}
// ... lines removed ...
public T pop() {
if(this.isEmpty())
throw new EmptyStackException();
return element(top--);
}
public T peek() {
if(this.isEmpty())
throw new EmptyStackException();
return element(top);
}
// Safe because push(T) is type checked.
#SuppressWarnings("unchecked")
private T element(int index) {
return (T)array[index];
}
}
Note also you have a bug in the resizeArray() method where maxSize is never assigned a new value. You don't really need to keep track of maxSize, as you could just use array.length.
I think there is also an issue with peek() when the stack is empty in the original code.
Your code creates arrays of StackArray, and then you try to stick Character objects in it, just as if you were doing this:
static void add(Object arr[], Object o) {
arr[0] = o;
}
public static void main(String[] args) {
StackArray stack[] = new StackArray[1];
Character c = 'x';
add(stack, c);
}
import java.util.Iterator;
public class MyArrayList<E> implements Iterable<E> {
public static final int DEFAULT_SIZE = 5;
public static final int EXPANSION = 5;
private int capacity;
private int size;
private Object[] items;
public MyArrayList() {
size = 0;
capacity = DEFAULT_SIZE;
items = new Object[DEFAULT_SIZE];
}
private void expand() {
Object[] newItems = new Object[capacity + EXPANSION];
for (int j = 0; j < size; j++) newItems[j] = items[j];
items = newItems;
capacity = capacity + EXPANSION;
}
public void add(Object obj) {
if (size >= capacity) this.expand();
items[size] = obj;
size++;
}
public int size() {
return size;
}
public Object get(int index) {
try{
return items[index];
} catch(IndexOutOfBoundsException e){
System.out.println("Exception Thrown: " + "Index is out of bound");
}
return index;
}
public boolean contains(Object obj) {
for (int j = 0; j < size; j++) {
if (obj.equals(this.get(j))) return true;
}
return false;
}
public void add(int index, Object obj) {
try{
if (size >= capacity) this.expand();
for (int j = size; j > index; j--) items[j] = items[j - 1];
items[index] = obj;
size++;
} catch(IndexOutOfBoundsException e){
System.out.println("Exception Thrown: " + "Index is out of bound");
}
return;
}
public int indexOf(Object obj) {
for (int j = 0; j < size; j++) {
if (obj.equals(this.get(j))) return j;
}
return -1;
}
public boolean remove(Object obj) {
for (int j = 0; j < size; j++) {
if (obj.equals(this.get(j))) {
for (int k = j; k < size-1; k++) items[k] = items[k + 1];
size--;
items[size] = null;
return true;
}
}
return false;
}
public Object remove(int index) {
try{
Object result = this.get(index);
for (int k = index; k < size-1; k++) items[k] = items[k + 1];
items[size] = null;
size--;
return result;
} catch(IndexOutOfBoundsException e){
System.out.println("Exception Thrown: " + "Index is out of bound");
}
return index;
}
public void set(int index, Object obj) {
try{
items[index] = obj;
} catch(IndexOutOfBoundsException e){
System.out.println("Exception Thrown: " + "Index is out of bound");
}
return;
}
public Iterator<E> iterator() {
return new MyIterator<E>();
}
public class MyIterator <T> implements Iterator<T>{
public boolean hasNext(){
}
public T next(){
}
public void remove(){
}
}
}
Basically I'm trying to improve the functionality of my arraylist, as it uses for loops for methods such as add and remove, however I am trying to use an iterator instead and I searched it up and I found out you cannot just simply add implements iterable to the main class, it has to be implemented by using three methods next(), hasNext() and remove(). I added the three methods at the bottom of the code but i'm really not sure how I implement it in order for it to begin to work.
You'll need to keep track of the index in the items array that the Iterator is on. Let's call it int currentIndex. hasNext() will return true if currentIndex < size. next() will increment currentIndex if hasNext() is true and return items[currentIndex], otherwise it should throw an Exception, say NoSuchElementException. Remove will call remove(currentIndex).
Here is an example (NOTE: I have not tried to compile this or anything so please update this post if you find any errors!)
public class MyArrayList<E> implements Iterable<E> {
...
#Override
public Iterator<E> iterator() {
return new Iterator<E>() {
private Object[] currentData = items;
private int pos = 0;
#Override
public boolean hasNext() {
return pos < currentData.length;
}
#Override
public E next() {
return (E) currentData[pos++];
}
#Override
public void remove() {
MyArrayList.this.remove(pos++);
}
};
}
}
You need to pass the items array to your MyIterator class so that you can keep track of the current position of the cursor in the array. Now based on the current position of the cursor you could implement all the abstract methods.
In the constructor of the MyIterator class pass the array as a parameter as public MyIterator(E[] array) and store the array as a local variable. also create a local variable cursor and set its value to 0.
I am using the following code to make an immutable queue.
import java.util.NoSuchElementException;
import java.util.Queue;
public class ImmutableQueue<E> {
//Two stacks are used. One is to add items to the queue(enqueue) and
//other is to remove them(dequeue)
private ImmutableQueue(ReversableStack<E> order, ReversableStack<E> reverse) {
this.order = order;
this.reverse = reverse;
}
//initially both stacks are empty
public ImmutableQueue() {
this.order = ReversableStack.emptyStack();
this.reverse = ReversableStack.emptyStack();
}
public ImmutableQueue<E> enqueue(E e) {
if (null == e)
throw new IllegalArgumentException();
return new ImmutableQueue<E>(this.order.push(e), this.reverse);
}
public ImmutableQueue<E> dequeue() {
if (this.isEmpty())
throw new NoSuchElementException();
if (!this.reverse.isEmpty()) {
return new ImmutableQueue<E>(this.order, this.reverse.tail);
} else {
return new ImmutableQueue<E>(ReversableStack.emptyStack(),
this.order.getReverseStack().tail);
}
}
private static class ReversableStack<E> {
private E head; //top of original stack
private ReversableStack<E> tail; //top of reversed stack
private int size;
//initializing stack parameters
private ReversableStack(E obj, ReversableStack<E> tail) {
this.head = obj;
this.tail = tail;
this.size = tail.size + 1;
}
//returns a new empty stack
public static ReversableStack emptyStack() {
return new ReversableStack();
}
private ReversableStack() {
this.head = null;
this.tail = null;
this.size = 0;
}
//Reverses the original stack
public ReversableStack<E> getReverseStack() {
ReversableStack<E> stack = new ReversableStack<E>();
ReversableStack<E> tail = this;
while (!tail.isEmpty()) {
stack = stack.push(tail.head);
tail = tail.tail;
}
return stack;
}
public boolean isEmpty() {
return this.size == 0;
}
public ReversableStack<E> push(E obj) {
return new ReversableStack<E>(obj, this);
}
}
private ReversableStack<E> order;
private ReversableStack<E> reverse;
private void normaliseQueue() {
this.reverse = this.order.getReverseStack();
this.order = ReversableStack.emptyStack();
}
public E peek() {
if (this.isEmpty())
throw new NoSuchElementException();
if (this.reverse.isEmpty())
normaliseQueue();
return this.reverse.head;
}
public boolean isEmpty() {
return size() == 0;
}
//returns the number of items currently in the queue
public int size() {
return this.order.size + this.reverse.size;
}
public static void main(String[] args)
{
ImmutableQueue<Integer> newQueue = new ImmutableQueue<Integer>();
newQueue.enqueue(5);
newQueue.enqueue(10);
newQueue.enqueue(15);
int x = newQueue.size();
//ImmutableQueue<Integer> x = newQueue.dequeue();
System.out.println(x);
}
}
But whenever I try to do a dequeue, I get a NoSuchElementException. Also, the newQueue.size function also returns 0.
What am I doing wrong ?
Thanks
You are missing the new ImmutableQueue reference..
since enqueue() method returns a new instance of ImmutableQueue
public ImmutableQueue<E> enqueue(E e) {
if (null == e)
throw new IllegalArgumentException();
return new ImmutableQueue<E>(this.order.push(e), this.reverse);
}
But on your main method you are discarding that object
public static void main(String[] args)
{
ImmutableQueue<Integer> newQueue = new ImmutableQueue<Integer>();
newQueue.enqueue(5);
newQueue.enqueue(10);
newQueue.enqueue(15);
int x = newQueue.size();
//ImmutableQueue<Integer> x = newQueue.dequeue();
System.out.println(x);
}
change your call to:
newQueue = newQueue.enqueue(5);
int x = newQueue.size();
System.out.println(x);
and you will see the size will change
I have three classes, those being Lister, ObjectSortedList and SortedListProgram. I'm having trouble with the iterator for the generic class. What am I doing wrong?
This is the error I get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at objectsortedlist.ObjectSortedList.getData(ObjectSortedList.java:122)
at objectsortedlist.Lister.hasNext(Lister.java:28)
at objectsortedlist.SortedListProgram.main(SortedListProgram.java:52)
Java Result: 1
Here are my classes:
package objectsortedlist;
import java.util.Iterator;
/**
*
* #author Steven
*/
public class ObjectSortedList<T> implements Cloneable, Iterable<T> {
private T[] data;
private int capacity;
public ObjectSortedList()
{
final int init_capacity = 10;
capacity = 0;
data = (T[])new Object[init_capacity];
}
public ObjectSortedList(int init_capacity)
{
if(init_capacity < 0)
throw new IllegalArgumentException("Initial capacity is negative: " + init_capacity);
capacity = 0;
data = (T[])new Object[init_capacity];
}
private boolean empty()
{
if(data.length == 0 || data[0] == null)
return true;
else
return false;
}
public int length()
{
return capacity;
}
public void insert(T element)
{
if(capacity == data.length)
{
ensureCapacity(capacity * 2 + 1);
}
data[capacity] = element;
capacity++;
}
public boolean delete(T target)
{
int index;
if(target == null)
{
index = 0;
while((index < capacity) && (data[index] != null))
index++;
}
else
{
index = 0;
while((index < capacity) && (!target.equals(data[index])))
index++;
}
if(index == capacity)
return false;
else
{
capacity--;
data[index] = data[capacity];
data[capacity] = null;
return true;
}
}
private void ensureCapacity(int minCapacity)
{
T[] placeholder;
if(data.length < minCapacity)
{
placeholder = (T[])new Object[minCapacity];
System.arraycopy(data, 0, placeholder, 0, capacity);
data = placeholder;
}
}
public ObjectSortedList<T> clone()
{
// Cloning
ObjectSortedList<T> answer;
try
{
answer = (ObjectSortedList<T>) super.clone();
}
catch(CloneNotSupportedException cnse)
{
throw new RuntimeException("This class does not implement cloneable.");
}
answer.data = data.clone();
return answer;
}
#Override
public Iterator<T> iterator()
{
return (Iterator<T>) new Lister<T>(this, 0);
}
public T getData(int index)
{
return (T)data[index];
}
}
package objectsortedlist;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
*
* #author Steven
*/
public class Lister<T> implements Iterator<T>
{
private ObjectSortedList<T> current;
private int index;
public Lister(ObjectSortedList<T> top, int index)
{
current = top;
this.index = index;
}
#Override
public boolean hasNext()
{
return (current.getData(index) == null);
}
#Override
public T next()
{
T answer;
if(!hasNext())
throw new NoSuchElementException("The Lister is empty.");
answer = current.getData(index+1);
return answer;
}
#Override
public void remove() {
throw new UnsupportedOperationException("Don't use this. Use objectsortedlist.SortedList.delete(T target).");
}
}
package objectsortedlist;
import java.util.Scanner;
/**
*
* #author Steven
*/
public class SortedListProgram {
private static Scanner scan = new Scanner(System.in);
private static String[] phraseArray = {"Hullabaloo!", "Jiggery pokery!", "Fantastic!", "Brilliant!", "Clever!", "Geronimo!", "Fish sticks and custard.", "Spoilers!",
"Exterminate!", "Delete!", "Wibbly-wobbly!", "Timey-wimey!"};
private static Lister<String> print;
public static void main(String args[])
{
int phraseNo = 0;
System.out.println("I'm gonna say some things at you, and you're going to like it."
+ " How many things would you like me to say to you? Put in an integer from 1-12, please.");
try
{
phraseNo = Integer.parseInt(scan.nextLine());
while((phraseNo < 1) || (phraseNo > 12))
{
System.out.println("The integer you entered wasn't between 1 and 12. Make it in between those numbers. Please? Pleaseeeee?");
phraseNo = Integer.parseInt(scan.nextLine());
}
}
catch(NumberFormatException nfe)
{
System.out.println("C'mon, why don't you follow directions?");
phraseNo = 0;
}
if(phraseNo == 0);
else
{
ObjectSortedList<String> phrases = new ObjectSortedList<String>(phraseNo);
for(int i = 0; i < phrases.length(); i++)
{
phrases.insert(phraseArray[i]);
}
print = new Lister<String>(phrases, phraseNo);
while(print.hasNext())
System.out.println(print.next());
}
}
}
After looking at your code I found multiple issues, here are they:
In your SortedListProgram class, in following code the phrases.length() will be 0, so the it will never go in that loop.
ObjectSortedList<String> phrases = new ObjectSortedList<String>(phraseNo);
for(int i = 0; i < phrases.length(); i++)
{
phrases.insert(phraseArray[i]);
}
Moreover in SortedListProgram class's this call sequence
print.hasNext() -> current.getData(index)
the index passed is equal to size of data array field in the
ObjectSortedList class and Since in java array indexes ranges from
zero to array size -1. So you are bound to get
java.lang.ArrayIndexOutOfBoundsException always.
Please correct your code.