Java, Generics, Merge, Comparable [duplicate] - java

This question already has an answer here:
Generics in Java, Merge method
(1 answer)
Closed 6 years ago.
Here is my question:
A method named merge that concatenates 2 unordered lists into a third. Assume that list_1 and list_2 don't have any keys in common. The resulting list should be an unsorted list that contains all of the items from list_1 and list_2 (preserve the order).
The problem that I am having is that I need to answer this question using generics. I have the code for the normal merge method which is the following..
// Merge Method
public OrderedArrayList merge(OrderedArrayList list2){
OrderedArrayList result = new OrderedArrayList(length + list2.length);
int list1Index = 0;
int list2Index = 0;
for (int i = 0; i < result.maxSize; i++) {
if (list1Index == list.length) {
result.insert(list2.list[list2Index]);
list2Index++;
} else if (list2Index == list2.length) {
result.insert(list[list1Index]);
list1Index++;
} else if (list[list1Index] < list2.list[list2Index]) {
result.insert(list[list1Index]);
list1Index++;
} else {
result.insert(list2.list[list2Index]);
list2Index++;
}
}
return result;
}
I have been working on the generics section for days. SOS!!
Here are my classes:
//Interface: ArrayListADT
//works for int
public interface ArrayListADT1<T> extends Comparable{
public boolean isEmpty(); //Method to determine whether the list is empty.
public boolean isFull(); //Method to determine whether the list is full.
public int listSize(); //Method to return the number of elements in the list.
public int maxListSize(); //Method to return the maximum size of the list.
public void print(); //Method to output the elements of the list.
public boolean isItemAtEqual(int location, T item); //Method to determine whether item is the same as the item in the list at location.
public void insertAt(int location, T insertItem); //Method to insert insertItem in the list at the position
public void insertEnd(T insertItem); //Method to insert insertItem at the end of the list.
public void removeAt(int location); //Method to remove the item from the list at location.
public T retrieveAt(int location); //Method to retrieve the element from the list at location.
public void replaceAt(int location, T repItem); //Method to replace the element in the list at location with repItem.
public void clearList(); //Method to remove all the elements from the list.
public int search(T searchItem); //Method to determine whether searchItem is in the list.
public void remove(T removeItem); //Method to remove an item from the list.
}
//Class: ArrayListClass1<T> implements
//Interface: ArrayListADT
public abstract class ArrayListClass1<T> implements ArrayListADT1<T>, Comparable{
protected int length; // to store the length of the list
protected int maxSize; // to store the maximum size of the list
protected T[] list; // array to hold the list elements
// Default constructor
public ArrayListClass1() {
maxSize = 100;
length = 0;
list = (T[]) new Object[maxSize];
}
// Alternate Constructor
public ArrayListClass1(int size) {
if (size <= 0) {
System.err.println("The array size must be positive. Creating an array of size 100.");
maxSize = 100;
} else
maxSize = size;
length = 0;
list = (T[]) new Object[maxSize];
}
public boolean isEmpty() {
return (length == 0);
}
public boolean isFull() {
return (length == maxSize);
}
public int listSize() {
return length;
}
public int maxListSize() {
return maxSize;
}
public void print() {
for (int i = 0; i < length; i++)
System.out.print(list[i] + " ");
System.out.println();
}
public boolean isItemAtEqual(int location, T item) {
if (location < 0 || location >= length) {
System.err.println("The location of the item to be compared is out of range.");
return false;
}
return list[location] == item;
}
public void clearList() {
for (int i = 0; i < length; i++)
list[i] = null;
length = 0;
System.gc(); // invoke the Java garbage collector
}
public void removeAt(int location) {
if (location < 0 || location >= length)
System.err.println("The location of the item to be removed is out of range.");
else {
for (int i = location; i < length - 1; i++)
list[i] = list[i + 1];
length--;
}
}
public T retrieveAt(int location) {
if (location < 0 || location >= length) {
System.err.println("The location of the item to be retrieved is out of range.");
return null;
} else
return list[location];
}
public abstract void insertAt(int location, T insertItem);
public abstract void insertEnd(T insertItem);
public abstract void replaceAt(int location, T repItem);
public abstract int search(T searchItem);
public abstract void remove(T removeItem);
}
//Class: OrderedArrayList1 extends
//Super class: ArrayListClass
public class OrderedArrayList1<T> extends ArrayListClass1<T>{
public OrderedArrayList1() {
super();
}
public OrderedArrayList1(int size) {
super(size);
}
// implementation for abstract methods defined in ArrayListClass
// ordered list --> binary search
public int search(T item) {
int first = 0;
int last = length - 1;
int middle = -1;
while (first <= last) {
middle = (first + last) / 2;
Comparable<T> listElem = (Comparable<T>) list[middle];
if (listElem.compareTo(item)==0)
return middle;
else
if (listElem.compareTo(item) > 0)
last = middle - 1;
else
first = middle + 1;
}
return -1;
}
public void insert(T item) {
int loc;
boolean found = false;
if (length == 0) // list is empty
list[length++] = item; // insert item and increment length
else if (length == maxSize) // list is full
System.err.println("Cannot insert in a full list.");
else {
for (loc = 0; loc < length; loc++) {
Comparable<T> temp = (Comparable<T>) list[loc];
if (temp.compareTo(item) >= 0) {
found = true;
break;
}
}
// starting at the end, shift right
for (int i = length; i > loc; i--)
list[i] = list[i - 1];
list[loc] = item; // insert in place
length++;
}
}
/*
* Another version for insert:
* public void insert(int item) {
* int loc;
* boolean found = false;
* if (length == 0) //list is empty
* list[length++] = item; //insert item and increment length
* else if (length == maxSize) //list is full
* System.err.println("Cannot insert in a full list.");
* else {
* int i = length - 1;
* while (i >= 0 && list[i] > item) {
* list[i + 1] = list[i];
* i--;
* }
* list[i + 1] = item; // Insert item
* length++;
* }
* }
*/
public void insertAt(int location, T item) {
if (location < 0 || location >= maxSize)
System.err.println("The position of the item to be inserted is out of range.");
else if (length == maxSize) // the list is full
System.err.println("Cannot insert in a full list.");
else {
System.out.println("Cannot do it, this is a sorted list. Doing insert in place (call to insert).");
insert(item);
}
}
public void insertEnd(T item) {
if (length == maxSize) // the list is full
System.err.println("Cannot insert in a full list.");
else {
System.out.println("Cannot do it, this is a sorted list. Doing insert in place (call to insert).");
insert(item);
}
}
public void replaceAt(int location, T item) {
// the list is sorted!
// is actually removing the element at location and inserting item in place
if (location < 0 || location >= length)
System.err.println("The position of the item to be replaced is out of range.");
else {
removeAt(location);// method in ArrayListClass
insert(item);
}
}
public void remove(T item) {
int loc;
if (length == 0)
System.err.println("Cannot delete from an empty list.");
else {
loc = search(item);
if (loc != -1)
removeAt(loc);// method in ArrayListClass
else
System.out.println("The item to be deleted is not in the list.");
}
}
/*
* Another version for remove:
* public void remove(T item) {
* int loc;
* if (length == 0)
* System.err.println("Cannot delete from an empty list.");
* else {
* loc = search(item);
* if (loc != -1) {
* for(int i = loc; i < length - 1; i++)
* list[i] = list[i + 1]; //shift left
* length--;
* }
* else
* System.out.println("The item to be deleted is not in the list.");
* }
* }
*/
/*
*
* KATHERINE'S
*
*/
// The start of Assignment 3
// Merge Method
public OrderedArrayList1<T> merge(OrderedArrayList1<T> list2){
OrderedArrayList1 result = new OrderedArrayList1(length + list2.length);
int list1Index = 0;
int list2Index = 0;
for (int i = 0; i < result.maxSize; i++) {
Comparable<T> temp = (Comparable<T>)list[list1Index];
T [] temp1 = new T list2[list1Index];
if (list1Index.equals(list[list1Index])) {
result.insert(list2.list[list2Index]);
list2Index++;
} else if (list2Index.equals(list[list1Index])) {
result.insert(list[list1Index]);
list1Index++;
}else if (temp.compareTo(list2) < 0) {
result.insert(list[list1Index]);
list1Index++;
} else {
result.insert(list2.list[list2Index]);
list2Index++;
}
}
return result;
}
// Split Method
public <T extends Comparable<T> > void split(OrderedArrayList1<T> lessThanKey, OrderedArrayList1<T> greaterThanKey, T splitKey) {
int i;
for (i = 0; i < length; i++) {
T temp = (T)list[i];
if (temp.compareTo(splitKey)<0)
lessThanKey.insert(temp);
else
greaterThanKey.insert(temp);
}
}
}
I have been working on the Merge Generics method for around 12 hours now. I have tried sooo many different ways. I would REALLY appreciate some help. Thank you!

Let's tackle this step by step.
First, you need to merge two lists together. This is only possible if the lists contain elements of the same type and, logically, the result will be a new list of the same type. So, we end up with the following method:
public <T extends Comparable<T>> List<T> merge(List<T> first, List<T> second) {
final List<T> merged = new ArrayList<T>();
merged.addAll(first);
merged.addAll(second);
return merged;
}
You just need to use your custom list implementation, but the principle is the same.
Second, when implementing your list, don't extend Comparable. You should only need that if you need to compare the instances of your class. Instead, make the elements comparable like in the example method.

Related

Why do we want to use a helper method in Java?

I came across this block of code when I was studying for java CS61b, which used a helper method. As to why we use helper method, the explanation I got is that it makes it easier to do the recursive task. But I have trouble visualizing the alternative options where we don't use a helper method because I have difficulting write the solution. Does that mean using a helper method is the only way? I wish I could compare the two solutions and better understand the usage of a helper method.
here's the code in question:
//Same as get, but uses recursion.
public int getRecursive(int index) {
if (index>size-1) {
return 0;
}
node p = sentinel;
return getRecursiveHelper(p, index);
}
public int getRecursiveHelper(node p, int i) {
if (i==0) {
return p.next.item;
} else {
p = p.next;
i -= 1;
}
return getRecursiveHelper(p, i);
}
the below is the full code:
public class LinkedListDeque {
public node sentinel;
public int size;
public class node {
public node prev;
public int item;
public node next;
public node(node p, int i, node n) {
prev = p;
item = i;
next = n;
}
}
// Creates an empty list
public LinkedListDeque() {
sentinel = new node(null, 63, null);
sentinel.prev = sentinel;
sentinel.next = sentinel;
size = 0;
}
// Adds an item of type T to the front of the deque.
public void addFirst(int x) {
sentinel.next = new node(sentinel, x, sentinel.next);
sentinel.next.next.prev = sentinel.next;
size += 1;
}
// Adds an item of type T to the back of the deque.
public void addLast(int x) {
sentinel.prev = new node(sentinel.prev, x, sentinel);
sentinel.prev.prev.next = sentinel.prev;
size += 1;
}
// Returns true if deque is empty, false otherwise.
public boolean isEmpty() {
if (size == 0) {
return true;
}
return false;
}
// Returns the number of items in the deque.
public int size() {
return size;
}
// Prints the items in the deque from first to last, separated by a space. Once all the items have been printed, print out a new line.
public void printDeque() {
node p = sentinel.next;
for (int i=0; i<size; i++) {
System.out.print(p.item + " ");
p = p.next;
}
System.out.println();
}
// Removes and returns the item at the front of the deque. If no such item exists, returns null.
public int removeFirst() {
if (size==0) {
return 0;
}
int x = sentinel.next.item;
sentinel.next = sentinel.next.next;
sentinel.next.prev = sentinel;
size -= 1;
return x;
}
// Removes and returns the item at the back of the deque. If no such item exists, returns null.
public int removeLast() {
if (size==0) {
return 0;
}
int x = sentinel.prev.item;
sentinel.prev = sentinel.prev.prev;
sentinel.prev.next = sentinel;
size -= 1;
return x;
}
// Gets the item at the given index, where 0 is the front, 1 is the next item, and so forth. If no such item e
public int get(int index) {
if (index>size-1) {
return 0;
}
node p = sentinel.next;
for (int i=0; i<index; i++) {
p = p.next;
}
return p.item;
}
//Same as get, but uses recursion.
public int getRecursive(int index) {
if (index>size-1) {
return 0;
}
node p = sentinel;
return getRecursiveHelper(p, index);
}
public int getRecursiveHelper(node p, int i) {
if (i==0) {
return p.next.item;
} else {
p = p.next;
i -= 1;
}
return getRecursiveHelper(p, i);
}
public static void main(String[] args) {
LinkedListDeque L = new LinkedListDeque();
L.addFirst(2);
L.addFirst(1);
L.addFirst(0);
L.addLast(3);
L.addLast(4);
L.addLast(5);
System.out.println(L.get(7));
}
}

The for each loop for the custom data type (ArrayList) with self implemented iterator does not run

import java.util.Arrays;
import java.util.Iterator;
public class ArrayList<Type> implements Iterable<Type> {
Type[] arr = (Type[]) new Object[10];
int size = 0;
//change capacity
public void newCapacity(int i) {
if (i == 0) {
int newIncreasedCapacity = arr.length * 2;
arr = Arrays.copyOf(arr, newIncreasedCapacity);
} else if (i == 1) {
int newDecreasedCapacity = arr.length / 2;
arr = Arrays.copyOf(arr, newDecreasedCapacity);
}
}
// add an item
public void add(Type item) {
if (size == arr.length) {
newCapacity(0);
}
arr[size++] = item; //increases size after appending
}
//remove an item
public Type remove(int index) {
if (size <= arr.length / 4) {
newCapacity(1);
}
Type removedItem = (Type) arr[index];
for (int i = index; i < size - 1; i++) {
arr[i] = arr[i + 1];
}
size -= 1;
return removedItem;
}
public int size() {
int count = 0;
for (int i = 0; i < size; i++) {
count += 1;
}
return count;
}
#Override
public Iterator<Type> iterator() {
return new ArrayIterator(arr);
}
class ArrayIterator<Type> implements Iterator<Type> {
private Type[] arrayList;
public ArrayIterator(Type[] newArray) {
arrayList = newArray;
}
// check if next element not null
public boolean hasNext() {
return (arrayList[size + 1] != null);
}
// next element
public Type next() {
if (arrayList[size + 1] != null) {
return (arrayList[size + 1]);
} else {
return null;
}
}
}
// Main Method
public static void main(String[] args) {
ArrayList<Integer> new_arr = new ArrayList<>();
new_arr.add(5);
new_arr.add(7);
new_arr.add(9);
new_arr.remove(0);
System.out.println(new_arr.size());
for (int i : new_arr) {
System.out.println(new_arr.size());
System.out.println(i);
}
}
}
I implemented the code for a custom ArrayList and also implemented an iterator for my custom data type, but I am facing an issue.
So when i run the for each loop in the main method, the loop does not run and thus nothing is printed on the console.I have checked the array which is being used for the for-each loop is not empty.Please help!
I think that you should fix your Iterator to something like
class ArrayIterator<Type> implements Iterator<Type> {
private Type[] arrayList;
private int position;
public ArrayIterator(Type[] newArray) {
arrayList = newArray;
position = 0;
}
// check if next element not null
public boolean hasNext() {
return (position != size);
}
// next element
public Type next() {
if (arrayList[position] != null) {
return (arrayList[position++]);
} else {
return null;
}
}
}
You are using the position of the size of the array to calculate the next() and hasNext(), the hasNext() is always returning null.

displaying circular queue in java

I have the following code where I have implemented a circular array. The problem comes when I try to display it. The display method works well until the array gets full and last goes back to 0. Therefore last and first are both 0 and the for loop doesn't execute.
public class PassengerQueue
{
private Passenger[] queueArray = new Passenger[TrainStation.WAITING_ROOM_CAPACITY];
private int first = 0;
private int last = 0;
private int maxStayInQueue = 0; //number of seconds that the passenger who stayed longest in the queue
private int maxLength = 0; //the maximum legth that was reached by the queue
private int currentSize = 0;
public void add(Passenger next)
{
//if the queue is not full - check for the circular queue
if (isFull()){
System.out.println("The queue is full");
}
else
{
queueArray[last] = next;
last = (last + 1) % queueArray.length;
currentSize++;
maxLength++;
}
}
public Passenger remove()
{
Passenger removedPassenger = null;
//if the queue array is not empty
//remove passenger
if (isEmpty())
{
System.out.println("The queue is empty");
}
else
{
removedPassenger = queueArray[first];
queueArray[first] = null;
first = (first + 1) % queueArray.length;
currentSize--;
}
return removedPassenger;
}
public Boolean isEmpty()
{
return (currentSize == 0);
}
public Boolean isFull()
{
return (currentSize == queueArray.length);
}
public void display()
{
if (isEmpty())
{
System.out.println("The queue is empty");
}
else
{
for(int i = first; i < last; i++)
{
queueArray[i].display();
}
}
}
Any help would be appreciated! Thank You
You can change the loop so it iterates from 0 to size. This also fixes the problem where last is less than first because items have been removed.
for(int i = 0; i < currentSize; i++)
{
queueArray[(first + i) % queueArray.length].display();
}
Just use the properties on the array itself to display:
public void display()
{
if (isEmpty())
{
System.out.println("The queue is empty");
}
else
{
for(int i = 0; i < queueArray.length; i++)
{
queueArray[i].display();
}
}
}

How can I fix my code to give the correct output instead of giving nothing?

When i run my code, i get nothing as my output. I suspect my code stops on this method:
public void deleteAt(int position)
{
if (position >= 0)
{
for (int i = position; i < theArray.length; i++)
{
theArray[i] = theArray[i + 1];
}
}
}
I think it stops at the above method because this code:
public int positionOf(char value)
{
//Search the list to find the value, if found return the position, if not, return -1
for (int i = 0; i < size(); i ++)
{
if (theArray[i] == value)
{
return i;
}
}
return -1;
}
only returns -1. If i remove the return -1; then Java thinks that there is an error because there is no return statment. I tried adding an else, but i still get the same error.
This is the whole code:
/** The interface for our List (Abstract Data Type) */
interface IList {
/** Adds the given value to the end of the list */
void append(char value);
/** Adds the given value to the beginning of the list */
void prepend(char value);
/** Deletes the container at the given position (a container holds a value) */
void deleteAt(int position);
/** Returns the number of values currently in our list */
int size();
/** Retrieves the value at the given position */
char getValueAt(int position);
/** Searches for the FIRST occurence of a given value in our list.
* If found, it returns the position of that value.
* If not found, it returns -1 */
int positionOf(char value);
}
/** Array implementation of our List */
class ListAsArray implements IList {
// initialize array to a size of 30 elements
// this will prevent the need to resize our array
char[] theArray = new char[30];
public void append(char value)
{
//Count until you find a place in the array that is empty, then insert
for (int i = 0; i < theArray.length; i ++)
{
if (theArray[i] == 0)
{
theArray[i] = value;
}
}
}
public void prepend(char value)
{
//Count until you find a empty value
for (int i = 0; i < theArray.length; i ++)
{
if (theArray[i] == 0)
{
//Once you find the empty value move everything over
for(int j = theArray.length; j != 0; j--)
{
theArray[i] = theArray[i + 1];
}
}
}
//Finally you want to actually add in the number in the first position
theArray[0] = value;
}
public void deleteAt(int position)
{
if (position >= 0)
{
for (int i = position; i < theArray.length; i++)
{
theArray[i] = theArray[i + 1];
}
}
}
public int size()
{
//Count until you find a place in the array that is empty, then return the number
int count = 0;
for (int i = 0; i < theArray.length; i ++)
{
if (theArray[i] == 0)
{
return count;
}
count ++;
}
return 0;
}
public char getValueAt(int position)
{
return theArray[position];
}
public int positionOf(char value)
{
//Search the list to find the value, if found return the position, if not, return -1
for (int i = 0; i < size(); i ++)
{
if (theArray[i] == value)
{
return i;
}
}
return -1;
}
}
/** Singly Linked List implementation of our List */
class ListAsLinkedList implements IList {
//Point to first node and second node
private Node head;
private Node tail;
//Constructor sets head and tail to null
public void LinkedList()
{
head = null;
tail = null;
}
public void append(char value)
{
//Wrap the data in a node
Node temp = new Node(value);
//Make this the first node if no other nodes
if (tail == null)
{
//Set tail to new node
tail = temp;
//Set head to new node
head = temp;
}
else
{
//Set new node to be after current end
tail.setNext(temp);
//Set as new tail
tail = temp;
}
}
public void prepend(char value)
{
//Wrap the data in a node
Node temp = new Node(value);
//Make this the first node if no other nodes
if (tail == null)
{
//Set tail to new node
tail = temp;
//Set head to new node
head = temp;
}
else
{
temp.next = head;
head = temp;
}
}
public void deleteAt(int position)
{
//Make the head node the next node if its the first one
if(position == 0)
{
head=head.next;
}
//If that wasn't the case...
Node current = head;
for(int i = 0; i < position-1; i++)
{
current = current.next;
}
current.next = current.next.next;
if(current.getNext() == null)
{
tail = current;
}
}
public int size()
{
Node temp = head;
for (int i = 0; i != 103; i++)
{
if (temp == tail)
{
return i;
}
}
return 0;
}
public char getValueAt(int position)
{
Node temp=head;
for(int i=0; i < position; i++)
{
temp=temp.next;
}
return temp.data;
}
public int positionOf(char value)
{
//Start at the beginning
int position = 0;
Node current = head;
//Look until we find target data
while (current.getData() != value)
{
//Move to next node
current = current.getNext();
//Increment position
position++;
}
//return position found
return position;
}
}
/** A singly linked list node for our singly linked list */
class Node {
//The node data and link to next node
public char data;
public Node next;
//Constructor
public Node(char data)
{
this.data = data;
this.next = null;
}
//Accessor
public char getData()
{
return data;
}
//Accessor
public Node getNext()
{
return next;
}
//Mutator
public void setData(char data)
{
this.data = data;
}
//Mutator
public void setNext(Node next)
{
this.next = next;
}
}
This is main:
/** contains our entry point */
public class Main {
/** entry point - DO NOT CHANGE the pre-existing code below */
public static void main(String[] args) {
int[] numbers = {105,116,112,115,65,58,47,47,116,105,110,121,88,117,114,108,46,99,111,109,47};
int[] numbers2 = {97,59,111,53,33,111,106,42,50};
int[] numbers3 = {116,104,32,111,116,32,111,71};
/// List as an Array
IList array = new ListAsArray();
// add values
for(int num : numbers) {
array.append((char)num);
}
for(int num : numbers3) {
array.prepend((char)num);
}
// delete some values
int position;
position = array.positionOf((char)105);
array.deleteAt(position);
position = array.positionOf((char)65);
array.deleteAt(position);
position = array.positionOf((char)88);
array.deleteAt(position);
// print em
position = 0;
while (position < array.size()) {
System.out.print(array.getValueAt(position));
position++;
}
/// List as a Linked List
IList linkedList = new ListAsLinkedList();
// add values
for(int num : numbers2) {
linkedList.append((char)num);
}
linkedList.prepend((char)55);
linkedList.prepend((char)121);
// delete some values
position = linkedList.positionOf((char)59);
linkedList.deleteAt(position);
position = linkedList.positionOf((char)33);
linkedList.deleteAt(position);
position = linkedList.positionOf((char)42);
linkedList.deleteAt(position);
// print em
position = 0;
while (position < linkedList.size()) {
System.out.print(linkedList.getValueAt(position));
position++;
}
System.out.println();
// ???
}
}
It should be outputting a link pertaining to the next part of my assignment.
The size() method always returns 0 according to your input.
size() method as per your code doesn't give you the length of the array to iterate over. Therefore you should use array length i.e theArray.length in positionOf() method's for loop instead of size() method.

Comparing attribute of an object in implementation of priority queue

I've attempted to implement a priority queue using an Array of Objects "Queue Items" which have some data (a string), and an integer which is the priority. I am trying to make those items comparable so that when I add a new object to the queue I can iterate through the items and add the new item in the correct location and move all items that are now behind it backwards, however when I add a new item to the queue I get a null pointer exception. I'll include all my code, but the toString method was just copied in from a queue so it won't work as expected.
class QueueItem implements Comparable<QueueItem> {
String data;
int pri;
public QueueItem(String data, int pri) {
this.data = data;
this.pri = pri;
}
#Override
public int compareTo(QueueItem item) {
return this.data.compareTo(item.data);
}
}
public class PriorityQueue implements Queue<String> {
private QueueItem[] arr;
private int frontPos, backPos;
public PriorityQueue() {
arr = new QueueItem[20];
backPos = -1;
frontPos = 0;
}
public boolean isEmpty() {
return frontPos == (backPos + 1) % arr.length;
}
public String front() {
if (frontPos == (backPos + 1) % arr.length)
throw new QueueException("Empty Queue - front");
return arr[frontPos].data;
}
public int frontPri() {
if (frontPos == (backPos + 1) % arr.length)
throw new QueueException("Empty Queue - frontPri");
return arr[frontPos].pri;
}
public void addToPQ(String str, int x) {
if (arr.length==0) {
arr[frontPos] = new QueueItem(str, x);
frontPos++;
return;
}
else {
for (int i = 0; i < arr.length; i++) {
arr[i].compareTo(new QueueItem(str, x));
}
}
}
public void deleteFront() {
if (frontPos==(backPos+1)%arr.length) {
throw new QueueException("Empty Queue - deleteFront");
}
frontPos = (frontPos+1)%arr.length;
}
public String toString() {
if (frontPos == (backPos + 1) % arr.length) {
return "<>";
}
StringBuffer sb = new StringBuffer();
sb.append('<');
int pos = frontPos;
while (pos != backPos) {
sb.append(arr[pos]);
sb.append(',');
pos = (pos + 1) % arr.length;
}
sb.append(arr[backPos]);
sb.append('>');
return (sb.toString());
}
}
public interface Queue<String> {
public void addToPQ(String str, int x);
public void deleteFront();
public String front();
public boolean isEmpty();
public int frontPri();
}
class QueueException extends RuntimeException {
QueueException(String s) {
super("Tried to apply " + s + " to empty queue");
}
}
public class pqTest {
public static void main(String[] args) {
PriorityQueue pQ = new PriorityQueue();
if (pQ.isEmpty()) {
System.out.println("Queue is Empty - isEmpty");
}
pQ.addToPQ("Dog", 4);
pQ.addToPQ("Cat", 20);
pQ.deleteFront();
pQ.addToPQ("Fish", 2);
}
}
The problem is that arr is size 20 so the first element won't even be added through the if statement in your addToPQ method because arr.length != 0. So it will then go to your else statement, which iterates through every single element in arr. But arr has 20 null elements since each spot within the array of QueueItems has not been initialized. So you should change your condition in the if statement to frontPos == 0 and change the terminating condition in your loop to i < frontPos so that the method won't iterate through null elements within arr
public void addToPQ(String str, int x) {
if (frontPos==0) {
arr[frontPos] = new QueueItem(str, x);
frontPos++;
return;
}
else {
QueueItem item = new QueueItem(str, x);
for (int i = 0; i < frontPos; i++) {
arr[i].compareTo(item);
}
}
}
You get NullPointerException, because when you are adding second item, you go to else statment where you iterate over array with one non-null element and 19 nulls. So you need to change your code to check if array element at i is null and if it is, assign new element to it.

Categories