I'm doing some school exercises about implementing interfaces and I've already got the workspace and Test classes provided for me. What I have to do is basically implement the methods, run the Test Classes, and make sure they pass the tests.
Here is my code: http://pastebin.com/e8Vh3snC
package queue;
import java.util.*;
public class FifoQueue<E> extends AbstractQueue<E> implements Queue<E> {
private QueueNode<E> last;
private int size=0;
private FifoQueue<E> queue;
public FifoQueue() {
queue = new FifoQueue<E>();
}
/**
* Returns an iterator over the elements in this queue
* #return an iterator over the elements in this queue
*/
public Iterator<E> iterator() {
return queue.iterator();
}
/**
* Returns the number of elements in this queue
* #return the number of elements in this queue
*/
public int size() {
return size;
}
/**
* Inserts the specified element into this queue, if possible
* post: The specified element is added to the rear of this queue
* #param x the element to insert
* #return true if it was possible to add the element
* to this queue, else false
*/
public boolean offer(E x) {
if(queue.add(x)){
size++;
return true;
} else {
return false;
}
}
/**
* Retrieves and removes the head of this queue,
* or null if this queue is empty.
* post: the head of the queue is removed if it was not empty
* #return the head of this queue, or null if the queue is empty
*/
public E poll() {
if(queue.size() > 0) {
size=size-1;
}
return queue.poll();
}
/**
* Retrieves, but does not remove, the head of this queue,
* returning null if this queue is empty
* #return the head element of this queue, or null
* if this queue is empty
*/
public E peek() {
return queue.peek();
}
private static class QueueNode<E> {
E element;
QueueNode<E> next;
private QueueNode(E x) {
element = x;
next = null;
}
}
}
Here are the Test Classes, in case you want to see them (provided by the school, so I doubt they're incorrect): http://pastebin.com/uV46j0rm
package testqueue;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.NoSuchElementException;
import java.util.Iterator;
import queue.FifoQueue;
public class TestFifoQueue {
private FifoQueue<Integer> myIntQueue;
private FifoQueue<String> myStringQueue;
#Before
public void setUp() throws Exception {
myIntQueue = new FifoQueue<Integer>();
myStringQueue = new FifoQueue<String>();
}
#After
public void tearDown() throws Exception {
myIntQueue = null;
myStringQueue = null;
}
/**
* Test if a newly created queue is empty.
*/
#Test
public final void testNewFifoQueue() {
assertTrue(myIntQueue.isEmpty());
assertTrue(myIntQueue.size() == 0);
}
/** Test a single offer followed by a single peek. */
#Test
public final void testPeek() {
myIntQueue.offer(1);
int i = myIntQueue.peek();
assertEquals("peek on queue of size 1", 1, i);
assertTrue(myIntQueue.size() == 1);
}
/**
* Test a single offer followed by a single poll.
*/
#Test
public final void testPoll() {
myIntQueue.offer(1);
int i = myIntQueue.poll();
assertEquals("poll on queue of size 1", 1, i);
assertTrue("Wrong size after poll", myIntQueue.size() == 0);
}
/**
* Test peek of empty queue.
*/
#Test
public final void testPeekOfEmpty() {
assertEquals("Front of empty queue not null", null, myIntQueue.peek());
}
/**
* Test poll of empty queue.
*/
#Test
public final void testPollOfEmpty() {
assertEquals("Poll of empty queue should return null", null, myIntQueue
.poll());
}
/**
* Test that implementation works for a queue of strings.
*/
#Test
public final void testStringQueue() {
myStringQueue.offer("First");
myStringQueue.offer("Second");
myStringQueue.offer("Third");
assertTrue("Wrong size of queue", myStringQueue.size() == 3);
assertEquals("peek on queue of strings", "First", myStringQueue.peek());
assertEquals("String First expected", "First", myStringQueue.poll());
assertEquals("String Second expected", "Second", myStringQueue.poll());
assertEquals("String Third expected", "Third", myStringQueue.poll());
assertTrue("Queue of strings should be empty", myStringQueue.isEmpty());
}
/**
* Test that polling gives elements in right order.
*/
#Test
public final void testOrder() {
myIntQueue.offer(1);
myIntQueue.offer(2);
myIntQueue.offer(3);
myIntQueue.offer(4);
myIntQueue.offer(5);
for (int i = 1; i <= 5; i++) {
int k = myIntQueue.poll();
assertEquals("poll returns incorrect element", i, k);
}
assertTrue("Queue not empty", myIntQueue.isEmpty());
}
/**
* Test that polling all elements gives an empty queue.
*/
#Test
public final void testMakeQueueEmpty() {
myIntQueue.offer(1);
myIntQueue.offer(2);
myIntQueue.poll();
myIntQueue.poll();
assertTrue("Wrong size after poll", myIntQueue.size() == 0);
assertTrue("Queue not empty after poll", myIntQueue.isEmpty());
myIntQueue.offer(3);
myIntQueue.offer(4);
assertTrue("Wrong size after offer", myIntQueue.size() == 2);
for (int i = 3; i <= 4; i++) {
int k = myIntQueue.poll();
assertEquals("poll returns incorrect element", i, k);
}
assertTrue("Wrong size after poll", myIntQueue.size() == 0);
assertTrue("Queue not empty after poll", myIntQueue.isEmpty());
}
}
So when I try to run the tests, I get multiple StackOverflowErrors at queue.FifiQueue.(FifoQueue.java:10)
I've been looking through the code for some hours now but can't figure out where I've written bad code.
PS: I know some of the methods are implemented incorrectly (I will try to fix them later) but as for now I'm just trying to pass the offer() och size() methods.
Your constructor is calling itself, causing infinite recursion:
public FifoQueue() {
queue = new FifoQueue<E>();
}
Maybe you mean to wrap some other type of queue or list internally?
Related
I need help to understand how the testing should go through. I should implement the test method in stacktest.java ( have already done that). Then extend Stacktest with LinkedlistTest ( i have already done that). Then add super.setUp() as the first line in LinkedListTest.setUp (I have done that). But the one overriden method is getIntegerStack that I implement in the LinkedListTest, but then i Get a error " 'getIntegerStack()' in 'LinkedListTest' clashes with 'getIntegerStack()' in 'StackTest'; attempting to use incompatible return type " I dont know how to fix it. I have tested but i dont want to import java.util.stack in StackTest.java, because then my top() method does not work. What should I do?
The testing:
StackTest.java is an abstract test class.
For each implementation of Stack, one may simply extend StackTest with an implementing test class. The only method that should be overridden is StackTest.getIntegerStack, which should simply return an instance of a class that implements Stack. See the setUp method in StackTest and try to understand how this works.
In your case, you should extend StackTest with a test class called LinkedListTest.
you must add a call to super.setUp(); as the first line in LinkedListTest.setUp.
TODO: How should i make the getIntegerStack() do work.
stack interface class:
public interface Stack <T> {
void push ( T elem);
T pop();
T top();
int size();
boolean isEmpty();
}
LinkedList class.
import java.util.EmptyStackException;
import java.util.NoSuchElementException;
/**
* A singly linked list.
*/
public class LinkedList<T> implements Stack <T> {
private ListElement<T> first; // First element in list.
private ListElement<T> last; // Last element in list.
private int size; // Number of elements in list.
/**
* A list element.
*/
private static class ListElement<T> {
public T data;
public ListElement<T> next;
public ListElement(T data) {
this.data = data;
this.next = null;
}
}
/**
* Creates an empty list.
*/
public LinkedList() {
this.first = null;
this.last = null;
this.size = 0;
}
/**
* Inserts the given element at the beginning of this list.
*
* #param element An element to insert into the list.
*/
public void addFirst(T element) {
ListElement<T> firstElement = new ListElement<>(element);
if (this.size == 0){
this.first = firstElement;
this.last = firstElement;
}
else{
firstElement.next = this.first;
this.first = firstElement;
}
this.size ++;
}
/**
* Inserts the given element at the end of this list.
*
* #param element An element to insert into the list.
*/
public void addLast(T element) {
ListElement<T> lastElement = new ListElement<>(element);
if(this.size ==0){
this.first = lastElement;
}
else{
this.last.next = lastElement;
}
this.last = lastElement;
this.size ++;
}
/**
* #return The head of the list.
* #throws NoSuchElementException if the list is empty.
*/
public T getFirst() {
if (this.first != null){
return this.first.data;
}
else{
throw new NoSuchElementException();
}
}
/**
* #return The tail of the list.
* #throws NoSuchElementException if the list is empty.
*/
public T getLast() {
if(this.last != null){
return this.last.data;
}
else{
throw new NoSuchElementException();
}
}
/**
* Returns an element from a specified index.
*
* #param index A list index.
* #return The element at the specified index.
* #throws IndexOutOfBoundsException if the index is out of bounds.
*/
public T get(int index) {
if(index < 0|| index >= this.size){
throw new IndexOutOfBoundsException();
}
else{
ListElement<T>element = this.first;
for(int i = 0; i < index; i++){
element = element.next;
}
return element.data;
}
}
/**
* Removes the first element from the list.
*
* #return The removed element.
* #throws NoSuchElementException if the list is empty.
*/
public T removeFirst() {
if(this.first != null || this.size != 0){
ListElement<T> list = this.first;
this.first = first.next;
size --;
if(size()==0){
last = null;
}
return list.data;
}
else{
throw new NoSuchElementException();
}
}
/**
* Removes all of the elements from the list.
*/
public void clear() {
this.first = null;
this.last = null;
this.size =0;
}
/**
* Adds the element to the top of the stock.
* #param elem
*/
#Override
public void push(T elem) {
ListElement <T> list = new ListElement<>(elem);
if( first == null){
first = list;
last = first;
} else{
list.next = first;
first = list;
}
size ++;
}
/**
* Removes and returns the top element in stack,
* that is the element that was last added.
* Throws an EmptyStackException if stack is empty.
* #return the top element in the stack.
*/
#Override
public T pop(){
if(isEmpty()){
throw new EmptyStackException();
}else{
ListElement <T> list = first;
first = first.next;
size --;
return list.data;
}
}
/**
* returns the top element in the stack without removing it.
* Throws an EmptyStackException if stack is empty.
* #return the top element.
*/
#Override
public T top() {
if(isEmpty()){
throw new EmptyStackException();
}else{
return first.data;
}
}
/**
* Returns the number of elements in the stock
* #return The number of elements in the stock.
*/
public int size() {
return this.size;
}
/**
* Note that by definition, the list is empty if both first and last
* are null, regardless of what value the size field holds (it should
* be 0, otherwise something is wrong).
*
* #return <code>true</code> if this list contains no elements.
*/
public boolean isEmpty() {
return first == null && last == null;
}
/**
* Creates a string representation of this list. The string
* representation consists of a list of the elements enclosed in
* square brackets ("[]"). Adjacent elements are separated by the
* characters ", " (comma and space). Elements are converted to
* strings by the method toString() inherited from Object.
*
* Examples:
* "[1, 4, 2, 3, 44]"
* "[]"
*
* #return A string representing the list.
*/
public String toString() {
ListElement<T> listOfElements = this.first;
String returnString = "[";
while(listOfElements != null) {
returnString += listOfElements.data;
if(listOfElements.next != null){
returnString += ", ";
}
listOfElements = listOfElements.next;
}
returnString += "]";
return returnString;
}
}
Testclasses:
import org.junit.Test;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.Timeout;
import static org.junit.Assert.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import java.lang.Integer;
import java.util.EmptyStackException;
import java.util.stream.IntStream;
/**
* Abstract test class for Stack implementations.
*
* Implementing test classes must only implement the getIntegerStack
* method. Be careful not to override ANY other methods!
*
*/
public abstract class StackTest{
#Rule public Timeout globalTimeout = Timeout.seconds(5);
private Stack<Integer> stack;
private int[] valuesInStack;
private int initialStackSize;
private Stack<Integer> emptyStack;
#Before
public void setUp() {
valuesInStack = new int[] {3, 4, 1, -123, 4, 1};
initialStackSize = valuesInStack.length;
stack = getIntegerStack();
pushArrayToStack(valuesInStack, stack);
emptyStack = getIntegerStack();
}
/**
* Push an array to the stack, in order.
*
* #param array An int array.
* #param stack A Stack.
*/
private void pushArrayToStack(int[] array, Stack<Integer> stack) {
for (int i = 0; i < array.length; i++) {
stack.push(array[i]);
}
}
/**
* This is the only method that implementing classes need to override.
*
* #return An instance of Stack.
*/
protected abstract Stack<Integer> getIntegerStack();
#Test
public void topIsLastPushedValue() {
// Arrange
int value = 1338;
// Act
emptyStack.push(value);
stack.push(value);
int emptyStackTop = emptyStack.top();
int stackTop = stack.top();
// Assert
assertThat(emptyStackTop, equalTo(value));
assertThat(stackTop, equalTo(value));
}
// HELPERS
/**
* Pops the desired amount of elements.
*
* #param stack A Stack.
* #param amountOfElements The amount of elements to pop.
*/
private void popElements(Stack<Integer> stack, int amountOfElements) {
for (int i = 0; i < amountOfElements; i++) {
stack.pop();
}
}
/**
* Class used for stream operations when both actual and expected values
* need to be gather in conjunction.
*/
private class ResultPair<T> {
public final T actual;
public final T expected;
public ResultPair(T actual, T expected) {
this.actual = actual;
this.expected = expected;
}
}
}
import org.junit.Test;
import org.junit.Before;
import static org.junit.Assert.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Stack;
/**
* Test class for LinkedList
*
* The following invariants are checked for several different states and for
* each of the methods that mutate the list.
*/
public class LinkedListTest extends StackTest{
/* A sequence of integers */
private int[] elements;
/* An empty linked list */
private LinkedList<Integer> list;
#Before
public void setUp() {
super.setUp();
list = new LinkedList<Integer>();
elements = new int[]{-919, 388, 67, -248, -309, -725, 904, 53,
90, -469, -559, 256, 612, 366, -412, -221,
347, -921, -978, 324, -858, 480, -443, 891,
329, -5, 878, -538, 445, -366, 760, 52};
}
/**
* This is the only method that implementing classes need to override.
*
* #return An instance of Stack.
*/
#Override
protected Stack<Integer> getIntegerStack() {
return null;
}
}
In StackTest your abstract method protected abstract Stack<Integer> getIntegerStack(); should return the Stack interface you created. At least that's what it looks like due to no imports of classes named Stack. But in LinkedListTest the method implementation returns java.util.Stack. Note this:
import java.util.Stack;
It's the last import in LinkedListTest.
The declared method is expecting implementors to return your.package.Stack, but you are returning java.util.Stack, and those need to match, no way around that. So remove the aforementioned import, there will be no more compilation errors, and you can start testing.
Edit:
If your Stack interface does not reside in any additional packages, you should just remove the import. If you have declared it in some package of your own, you should change the import to
import your.package.Stack;
where your.package. is whatever package you declared the interface in.
About the implementation of the abstract method, you should return a new instance of Stack, as written in the comments. That means returning new instance of your LinkedList implementation.
I wrote these codes in Idea. The IDE throws "can't resolve method get in Deque.java" when I finished Palindrome.java. How come? I actually did that in the Deque.java. Although in the LinkedListDeque inherited the get() method from the origin LinkList.
I found another solution by changing
Deque stringDeque = wordToDeque(word);
to
LinkListDeque stringDeque = (LinkListDeque) wordToDeque(word);
But I am still curious about how cannot find get in Deque.
class diagram here
Deque interface
/** Create an interface in a new file named Deque.
* java that contains all of the methods that appear in both ArrayDeque and LinkedListDeque.
* #param <Item>
*/
public interface Deque<Item> {
int size = 0;
/** Adds an item of type T to the front of the deque. */
void addFirst(Item item);
/** Adds an item of type T to the back of the deque. */
void addLast(Item item);
/** Returns true if deque is empty, false otherwise. */
default boolean isEmpty() {
return size == 0;
};
/** 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. */
void printDeque();
/** Removes and returns the item at the front of the deque. If no such item exists, returns null. */
Item removeFirst();
/** Removes and returns the item at the back of the deque. If no such item exists, returns null. */
Item removeLast();
/** Gets the item at the given index, where 0 is the front, 1 is the next item, and so forth.
* If no such item exists, returns null. Must not alter the deque! */
Item get(int index);
}
class LinkedLinkDeque.java
import java.util.LinkedList;
import java.util.NoSuchElementException;
/**
* Isn't this solution kinda... cheating? Yes.
*/
public class LinkedListDeque<Item> extends LinkedList<Item> implements Deque<Item> {
#Override
public void printDeque() {
System.out.println("dummy");
}
public Item getRecursive(int i) {
return get(i);
}
#Override
public Item removeFirst() {
try {
return super.removeFirst();
} catch (NoSuchElementException e) {
return null;
}
}
#Override
public Item removeLast() {
try {
return super.removeLast();
} catch (NoSuchElementException e) {
return null;
}
}
}
Palindrome.java
import java.util.Deque;
import java.util.LinkedList;
public class Palindrome {
/** Given a String, wordToDeque should return a Deque
* where the characters appear in the same order as in the String.
* #param word
*/
public Deque<Character> wordToDeque(String word) {
Deque<Character> stringDeque = new LinkedListDeque<>();
for (String s : word.split("")) {
stringDeque.addLast(s.charAt(0));
}
return stringDeque;
}
/** Return true if the given word is a palindrome, and false otherwise. */
public boolean isPalindrome(String word) {
if (word.length() == 0 || word.length() == 1) {
return true;
}
Deque stringDeque = wordToDeque(word);
int index = word.length() / 2;
for (int i = 0; i < index; i += 1) {
if (stringDeque.get(i) != stringDeque.get(word.length() - i - 1)) { return false; }
}
return true;
}
}
You have your own Deque interface but you are also working with the java.util.Deque interface. This can result in problems as the interface Deque is defined twice in different namespaces. Specially in your Palindrome.java file you are using the java.util.Deque interface because of the import java.util.Deque line at the top and NOT your Deque interface as you might expect.
Because of that you get the error message that the get(int) method is missing. That is correct, the java.util.Deque method does not define a get(int) method (but the java.util.List interface does).
Do not name classes with names which already exists in java. As you see that can result in naming conflict/issues.
I'm trying to implement a Queue but my method "enqueue(E e)" is giving me an error saying that the method clashes with the method in the Queue interface but neither override the other. What is going on?
Here is the Queue Interface
public interface Queue<E> {
/**
* Returns the number of elements in the queue.
*/
int size();
/**
* Tests whether the queue is empty.
*/
boolean isEmpty();
/**
* Inserts an element at the rear of the queue.
*/
void enqueue(E e);
/**
* Returns, but does not remove, the first element of the queue (null if empty).
*/
E first();
/**
* Removes and returns the first element of the queue (null if empty).
*/
E dequeue();
}
And here is the implementation
/**
* Implementation of the queue ADT using a fixed-length array.
* #param <E>
*/
public class ArrayQueue<E> implements Queue {
// instance variables
private E[] data;
private int f = 0;
private int sz = 0;
public static final int CAPACITY = 1000;
// Constructors
public ArrayQueue() {
this(CAPACITY);
}
public ArrayQueue(int capacity) {
data = (E[]) new Object[capacity];
}
// methods
/**
* Returns the number of elements in the queue
*/
public int size() {
return sz;
}
/**
* Tests whether the queue is empty.
*/
public boolean isEmpty() {
return sz == 0;
}
/**
* Inserts an element at the rear of the queue.
*/
public void enqueue(E e) throws IllegalStateException {
if (sz == data.length)
throw new IllegalStateException("Queue is full");
int avail = (f + sz) % data.length;
data[avail] = e;
sz++;
}
/**
* Returns, but does not remove, the first element of the queue (null if empty)
*/
public E first() {
if (isEmpty())
return null;
return data[f];
}
/**
* Removes and returns the first element of the queue (null if empty)
*/
public E dequeue() {
if (isEmpty())
return null;
E answer = data[f];
data[f] = null;
f = (f + 1) % data.length;
sz--;
return answer;
}
}
I've tried removing the "throws new IllegalStateError" and copy and pasting to make sure the spelling was the same. I can't figure out what the problem is. Both of these code fragments come straight out of a book...
I have a static ArrayList (masterLog) that is in my main driver class. The ArrayList contains Event objects, the Event object has an ArrayList (heats) as a global variable. the heat object as an ArrayList (racers) as a global variable. Now when I have the following line of code:
System.out.println(ChronoTimer1009System.getMasterLog().get(0).getHeats().get(getCurHeat()).getRacers().toString());
this returns [] even though the getRacers() IS NOT empty!
When I call this:
System.out.println(getHeats().get(getCurHeat()).getRacers());
this returns the proper filled array.
I think I need to sync the masterLog ArrayList but I am unsure how. I have tried syncing it the way other threads on Stack Exchange have recommended but no luck.
it seems like the static ArrayList masterLog is updated two levels deep but not three levels deep if that makes sense.
What am I doing wrong?
UPDATE:
Maybe this will help explain:
In my main (driver) class, I have a static ArrayList called masterLog. The purpose of this ArrayLIst is to store instances of Event objects for later data retrieval. Now, without making it too complicated, the Event class contains an ArrayList called heats, and the Heat class contains an ArrayList called racers. When I access the masterLog ArrayList at some point in the program (when the other ArrayLists are populated with data), say for example by the call "masterLog.getHeats().get(0).getRacers()", the masterLog does not find any data in the racers ArrayList. It does, however, find data in the heats ArrayList. In other words, the object instance that is stored in the masterLog only updates information to a depth of 2 (not 3 if that makes sense).
UPDATE:
Here is some code:
ChronoTimer1009System class (driver)
package main;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Stack;
public class ChronoTimer1009System {
private Event curEvent;
private static Channel[] channels = new Channel[8];
private boolean state;
private static Stack<Log> log;
private static ArrayList<Event> masterLog;
private static Printer p;
public static Time globalTime;
private int oldLogSize; //used only in this.export()
public ChronoTimer1009System() throws UserErrorException{
for(int i=0; i<channels.length; ++i){channels[i] = new Channel(SensorType.NONE);} // initialize channels
masterLog = new ArrayList<Event>(); //this holds references to each event
this.newEvent(EventType.IND);
this.state = false; //system is initally off
log = new Stack<Log>();
p = new Printer();
globalTime = null;
oldLogSize = 0;
}
public void newEvent(EventType e) throws UserErrorException {
switch(e){
case IND: this.curEvent = new IND();ChronoTimer1009System.masterLog.add(this.curEvent);break;
case PARIND: this.curEvent = new PARIND();ChronoTimer1009System.masterLog.add(this.curEvent);break;
case GRP: this.curEvent = new GRP();ChronoTimer1009System.masterLog.add(this.curEvent);break;
case PARGRP: this.curEvent = new PARGRP();ChronoTimer1009System.masterLog.add(this.curEvent);break;
}
for(Channel x : channels){if(x.getState()) x.toggleState();}
}
public void on() throws UserErrorException{
if(state) throw new IllegalStateException();
this.curEvent = new IND();
ChronoTimer1009System.globalTime = new Time(0);
state = true;
}
public void reset() throws UserErrorException{
if(state) state = false;
on();
}
public void exit(){
this.curEvent = null;
ChronoTimer1009System.globalTime = null;
if(!state) throw new IllegalStateException();
state = false;
}
public static Time searchElapsedByID(int idNum){
Time toReturn = null;
for(Log item : log){
if(item.getCompetitorNumber() == idNum){
toReturn = item.getElapsedTime(); break;
}
}
return toReturn;
}
/**
* #return the curEvent
*/
public Event getCurEvent() {
return curEvent;
}
/**
* #return the state
*/
public boolean isState() {
return state;
}
public static Channel getChan(int chan){
if(chan < 1 || chan > 8) throw new IllegalArgumentException("Argument is not in range");
return channels[chan-1];
}
public static void export(){
//*****FORMAT JSON*****
//before formating, a sort of the runners within each heat is needed to determine place.
String toJson = "{\"events\":[";
System.out.println(ChronoTimer1009System.getMasterLog().get(0).getHeats().get(0).getRacers().size());
//iterate through each event
for(int i = 0; i < ChronoTimer1009System.getMasterLog().size(); ++i){
//iterate through each heat of each event
toJson += "{\"name\":\"" + ChronoTimer1009System.getMasterLog().get(i).getType().toString() + "\",\"heats\":[";
for(int j = 0; j < ChronoTimer1009System.getMasterLog().get(i).getHeats().size(); ++j){
//iterate through each competitor in each heat
toJson += "{\"runners\":[";
System.out.println(ChronoTimer1009System.getMasterLog().get(i).getHeats().size());
ArrayList<Competitor> x = sortByPlace(ChronoTimer1009System.getMasterLog().get(i).getHeats().get(j).getRacers()); <----- on this line, the getRacers() part has a size of zero when it isn't empty.
for(int k = 0; k < x.size(); ++k){
//notice we are working with a sorted copy
//TODO make Competitor endTime the elapsed time
toJson += "{\"place\":\"" + String.valueOf(k+1) + "\",\"compNum\":\"" + x.get(k).getIdNum() + "\", \"elapsed\":\"" + x.get(k).getEndTime().toString() + "\"},";
}
toJson += "]},";
}
toJson += "]},";
}
toJson += "}";
System.out.println(toJson);
/*try{
URL site = new URL("http://7-dot-eastern-cosmos-92417.appspot.com/chronoserver");
HttpURLConnection conn = (HttpURLConnection) site.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
String data = "data=" + toJson;
out.writeBytes(data);
out.flush();
out.close();
System.out.println("Done sent to server");
new InputStreamReader(conn.getInputStream());
}
catch (Exception e)
{
e.printStackTrace();
}*/
}
private static ArrayList<Competitor> sortByPlace(ArrayList<Competitor> unsorted)
{
ArrayList<Competitor> whole = (ArrayList<Competitor>) unsorted.clone();
ArrayList<Competitor> left = new ArrayList<Competitor>();
ArrayList<Competitor> right = new ArrayList<Competitor>();
int center;
if(whole.size()==1)
return whole;
else
{
center = whole.size()/2;
// copy the left half of whole into the left.
for(int i=0; i<center; i++)
{
left.add(whole.get(i));
}
//copy the right half of whole into the new arraylist.
for(int i=center; i<whole.size(); i++)
{
right.add(whole.get(i));
}
// Sort the left and right halves of the arraylist.
left = sortByPlace(left);
right = sortByPlace(right);
// Merge the results back together.
merge(left,right,whole);
}
return whole;
}
private static void merge(ArrayList<Competitor> left, ArrayList<Competitor> right, ArrayList<Competitor> whole) {
int leftIndex = 0;
int rightIndex = 0;
int wholeIndex = 0;
// As long as neither the left nor the right arraylist has
// been used up, keep taking the smaller of left.get(leftIndex)
// or right.get(rightIndex) and adding it at both.get(bothIndex).
while (leftIndex < left.size() && rightIndex < right.size())
{
if ((left.get(leftIndex).getEndTime().compareTo(right.get(rightIndex)))<0)
{
whole.set(wholeIndex,left.get(leftIndex));
leftIndex++;
}
else
{
whole.set(wholeIndex, right.get(rightIndex));
rightIndex++;
}
wholeIndex++;
}
ArrayList<Competitor>rest;
int restIndex;
if (leftIndex >= left.size()) {
// The left arraylist has been use up...
rest = right;
restIndex = rightIndex;
}
else {
// The right arraylist has been used up...
rest = left;
restIndex = leftIndex;
}
// Copy the rest of whichever arraylist (left or right) was
// not used up.
for (int i=restIndex; i<rest.size(); i++) {
whole.set(wholeIndex, rest.get(i));
wholeIndex++;
}
}
/**
* #return the log
*/
public static Stack<Log> getLog() {
return log;
}
/**
* #return the masterLog
*/
public static ArrayList<Event> getMasterLog() {
return masterLog;
}
/**
* #return the p
*/
public static Printer getPrinter() {
return p;
}
}
Event Class:
package main;
import java.util.ArrayList;
public abstract class Event extends Display{
private ArrayList<Heat> heats;
private int curHeat; //private means only this class can modify, not the subclasses
private Competitor curComp;
private String name;
public Event(String name) throws UserErrorException{
this.name = name;
heats = new ArrayList<Heat>();
curHeat = -1;
curComp = null;
createRun();
}
/**
* This method will be used by all EventTypes and will not change
* regardless of the EventType.
* #throws UserErrorException
*/
public void createRun() throws UserErrorException{
heats.add(new Heat()); ++curHeat;
}
/**
* #return the heats
*/
public ArrayList<Heat> getHeats() {
return heats;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #return the currentHeat
*/
public int getCurHeat() {
return curHeat;
}
/**
* #return the curComp
*/
public Competitor getCurComp() {
return curComp;
}
/**
* #param curComp the curComp to set
*/
public void setCurComp(Competitor curComp) {
this.curComp = curComp;
}
/* (non-Javadoc)
* #see Display#displayHeatNumber()
*/
#Override
public String displayHeatNumber() {
// TODO Auto-generated method stub
return "Heat: " + (curHeat+1);
}
/* (non-Javadoc)
* #see Display#displayFinished()
*/
#Override
public String displayFinished() {
String toReturn = "";
boolean noRunners = true;
for(Competitor x : getHeats().get(getCurHeat()).getRacers()){
if(x.getEndTime() != null){
toReturn += "\n" + x.getIdNum() + " " + (ChronoTimer1009System.searchElapsedByID(x.getIdNum()).equals(new Time(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE)) ? "DNF" : ChronoTimer1009System.searchElapsedByID(x.getIdNum()).toString() + " F");
noRunners = false;
}
}
if(noRunners){toReturn = "no runners have finished";}
return toReturn;
}
public abstract void endRun() throws UserErrorException;
public abstract void trigChan(int chan, boolean dnf) throws UserErrorException;
public abstract void cancel(int ln) throws UserErrorException;
public abstract EventType getType();
}
Heat class:
package main;
import java.util.ArrayList;
public class Heat {
private ArrayList<Competitor> racers;
//private ArrayList<Competitor> racers;
private int currentCompetitor;
/**
* Constructor
*/
public Heat(){
racers = new ArrayList<Competitor>();
//racers = new ArrayList<Competitor>();
currentCompetitor = 0;
}
/**
* Set selected racer as next on to start
* #param racer the racer to start next
*/
public void setNextCompetitor(Competitor x){
int pos = racers.indexOf(x);
if(pos == -1 || pos<currentCompetitor) throw new IllegalArgumentException("Competitor not in the race! Please add first");
for(int i = pos; i>currentCompetitor; --i){
racers.set(i, racers.get(i-1));
}
racers.set(currentCompetitor, x);
}
/**
* Take the selected runner (the next runner) out from the race
* #param racer the runner to be cleared
*/
public void clearNextCompetitor() throws UserErrorException {
if(racers.size()-(currentCompetitor)<1) throw new UserErrorException("No runners to clear!");
for(int i = currentCompetitor+1; i<racers.size(); ++i){
racers.set(i-1, racers.get(i));
}
racers.remove(racers.size()-1);
}
/**
* basically a remove method
* #param x
*/
public void remove(Competitor x){
int pos = racers.indexOf(x);
if(pos < 0) throw new IllegalArgumentException("runner does not exists");
racers.remove(pos);
}
/**
* Swaps two runners positions in line
*/
public void swap() throws UserErrorException{
int count = 0;
for(Competitor x : racers){
if(x.getStartTime() == null) ++count;
}
if(count > 1 && currentCompetitor + 1 <= racers.size()){
Competitor first = racers.get(currentCompetitor);
Competitor second = racers.get(currentCompetitor+1);
racers.set(currentCompetitor, second);
racers.set(currentCompetitor+1, first);
}
else{
throw new UserErrorException("Not enough competitors to swap");
}
}
/**
* Add a competitor to the end of the current line of competitors if any
* #param x the competitor to add
*/
public boolean addCompetitor(Competitor x) throws UserErrorException{
if(x.getIdNum() < 0 || x.getIdNum() > 99999) throw new UserErrorException("ID number out of range");
if(x.getRunNum() < 0) throw new IllegalArgumentException("Run Num Out of range");
boolean add = true;
for(Competitor i : racers){
if(i.getIdNum() == x.getIdNum()){
add = false;
break;
}
}
if(add){
racers.add(x);
}
return add;
}
/**
* Retrieve the next competitor if there is one
* #return the next competitor
*/
public Competitor getNextCompetitor() throws UserErrorException{
if(!hasNextCompetitor()) throw new UserErrorException("There are no more competitors!");
while(racers.get(currentCompetitor).isCompeting()){++currentCompetitor;}
return racers.get(currentCompetitor++);
}
/**
* used to fix the order of the queue after cancel is called
*/
public void fix(EventType x){
switch(x){
case IND:
--currentCompetitor;
break;
case GRP: case PARGRP: case PARIND:
for(int i = 0; i<racers.size(); ++i){
if(racers.get(i).getStartTime() == null){
currentCompetitor = i;
break;
}
}
break;
}
}
/**
* Is there another competitor to go?
* #return whether or not there is another competitor to go.
*/
public boolean hasNextCompetitor(){
return currentCompetitor < racers.size();
}
/**
* Return a 1D array view of the competitors
* #return
*/
public ArrayList<Competitor> getRacers(){
return racers;
}
}
in the export method of the ChronoTimer1009System class, I point out where the error is and what is happening
The question is nested inside the code. I have 2 code options. Each listed with pros and cons. Wanted to know a preferred approach.
OPTION1:
public class Graph {
private final List<ArrayList<Integer>> adjList;
/**
* DISADVANTAGE:
* 1. Slow to create an object.
* 2. Memory allocated prematurely, lazy initialization could be used to speed up object creation.
*/
public Graph(int vertexCount) {
adjList = new ArrayList<ArrayList<Integer>>(vertexCount);
for (int i = 0; i < vertexCount; i++) {
adjList.add(new ArrayList<Integer>());
}
this.vertexCount = vertexCount;
}
/**
* ADVANTAGE:
* 1. No synchronization issues, reducing complexity and overhead of sync.
* 2. No need to null check, since constructor has taken care of lot .
*/
public void addEdge(int vertexFrom, int vertexTo) {
adjList.get(vertexFrom).add(vertexTo);
adjList.get(vertexTo).add(vertexFrom);
}
/**
* DISADVANTAGE:
*
* Inspite of knowing that none of the List<Integers> are null, an extra check for size == 0, needed to return Collections.EMPTY_LIST
* Eg:
* if (adjList.get(vertex).size == 0) { return Collections.EMPTY_LIST; }
* return adjList.get(vertex).size
*/
public List<Integer> adj(int vertex) {
return adjList.get(vertex);
}
}
OPTION 2
public class Graph {
private final List<ArrayList<Integer>> adjList;
private final int vertexCount;
private int edgeCount;
/**
* ADVANTAGE: quick construction
*
*/
public Graph(int vertexCount) {
adjList = new ArrayList<ArrayList<Integer>>(vertexCount);
this.vertexCount = vertexCount;
}
/**
* DISADVANTAGE:
* 1. Effort spent on null checks.
*
* 2. Thread safety complications.
*/
public void addEdge(int vertexFrom, int vertexTo) {
if ( adjList.get(vertexFrom) == null ) {
adjList.add(vertexFrom, new ArrayList<Integer>())
}
if ( adjList.get(vertexTo) == null ) {
adjList.add(vertexTo, new ArrayList<Integer>())
}
adjList.get(vertexFrom).add(vertexTo);
adjList.get(vertexTo).add(vertexFrom);
edgeCount++;
}
public List<Integer> adj(int vertex) {
if (adjList.get(vertex) == 0) return Collections.EMPTY_LIST;
return adjList.get(vertex);
}
public List<ArrayList<Integer>> getGraph() {
return adjList;
}
}