Queue12 is an interface, QueueImp12 is an implementation of Queue12. So i'm trying to test my QueueImp12 but when i run it(it compiles) in eclipse my output gets terminated in console. I believe I created ringBuffer correctly. If my test looks fine, then something must be wrong with my implementation or eclipse. Thanks
import java.util.NoSuchElementException;
public class QueueImpl12<T> implements Queue12<T>
{
private int _size, _backIdx, _frontIdx;
private static final int _defaultCapacity = 128;
private T[] _ringBuffer;
public QueueImpl12(int capacity)
{
_ringBuffer = (T[]) new Object[capacity];
clear();
}
public QueueImpl12()
{
_ringBuffer = (T[]) new Object[_defaultCapacity];
clear();
}
private int wrapIdx(int index)
{
return index % capacity();
}
public void clear()
{
_backIdx = 0;
_frontIdx = 0;
_size = 0;
}
#Override
public int capacity()
{
// TODO Auto-generated method stub
return _ringBuffer.length;
}
#Override
public int size()
{
// TODO Auto-generated method stub
return _size;
}
#Override
public boolean enqueue(T o)
{
//add o to back of queue
if(_ringBuffer.length == _size)
{
return false;
}
_ringBuffer[_backIdx] = o;
_backIdx = wrapIdx(_backIdx + 1 );
_size++;
return true;
}
#Override
public T dequeue()
{
if(_size == 0) //empty list
{
throw new NoSuchElementException();
}
T tempObj = _ringBuffer[_frontIdx]; //store frontIdx object
_ringBuffer[_frontIdx] = null;
_frontIdx++;
_size--;
return tempObj;
}
#Override
public T peek()
{
return _ringBuffer[_frontIdx];
}
}
public class P3test
{
public static<T> void main(String[] args)
{
final Queue12<T> ringBuffer = new QueueImpl12<T>();
T o = (T) new String("this");
ringBuffer.enqueue(o); //add element to the back
ringBuffer.dequeue(); //remove/return element in the front
}
}
That 'terminated' you have been seeing lately is the expected behavior when your program finishes.
Put some System.outs or asserts to verify that your code runs (here it runs, with some awful cast warnings, but runs)
final Queue12<T> ringBuffer = new QueueImpl12<T>();
T o = (T) new String("this");
ringBuffer.enqueue(o); //add element to the back
System.out.println(ringBuffer.peek());//this should print 'this' in the console\
//assertEquals('this', ringBuffer.peek());
ringBuffer.dequeue(); //remove/return element in the front
Learn how to use generics and tests. And don't put generic argument in main function, is is useless there.
Related
public class StackSimple{
private long capacity=1000;//maximum size of array
private int idx_top;
private Object data[];
public StackSimple(int capacity)
{
idx_top=-1;
this.capacity=capacity;
data = new Object[capacity];
}
public boolean isEmpty(){
return(idx_top<0);
}
public boolean isFull(){
return(idx_top>=capacity-1);
}
public int size()
{
return idx_top+1;
}
public boolean push(Object x){
if (isFull()){
throw new IllegalArgumentException("ERROR:Stack Overflow.Full Stack");
}
else
{`enter code here`data[++idx_top]=x;
return true;
}
}
public Object pop(){
if(isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else{
return data[idx_top--];
}
}
public Object top(){
if (isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else{
return data[idx_top];
}
}
public void print()
{`
for (int i=size()-1;i>=0;i--)
System.out.println(data[i]);
}
}
public class Stack_Exercise {
public static void main(String[] args) {
StackSimple s = new StackSimple(capacity:3);//error shows here
s.push(x:"books");`enter code here`
s.push(x:"something");
s.push(x:"200");
s.print();
System.out.println("Size=" +s.size());
}
}
Why doesn't this work?
Why does it say invalid statement while creating the StackSimple object? The problem is in the main class while running it. There are errors while pushing the elements.
Error while compiling
When passing parameters to a function you just pass the values.
In your case not StackSimple(capacity:3) but just StackSimple(3)
First question, which version of Java are you using.
Second, in Java you should be passing as a variable instead of StackSimple(capacity:3). Change your main method to below, here is my recommendation:
StackSimple s = new StackSimple(3);
s.push("books");
s.push("something");
s.push("200");
s.print();
System.out.println("Size=" +s.size());
You are not at all pushing the value in the stack, your pusch function is not working as it is expected to work.
Here is the correct program.
class StackSimple {
private long capacity = 1000;// maximum size of array
private int idx_top;
private Object data[];
public StackSimple(int capacity) {
idx_top = -1;
this.capacity = capacity;
data = new Object[capacity];
}
public boolean isEmpty() {
return (idx_top < 0);
}
public boolean isFull() {
return (idx_top >= capacity - 1);
}
public int size() {
return idx_top + 1;
}
public boolean push(Object x) {
if (isFull()) {
throw new IllegalArgumentException("ERROR:Stack Overflow.Full Stack");
} else {
data[++idx_top] = x;
return true;
}
}
public Object pop() {
if (isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else {
return data[idx_top--];
}
}
public Object top() {
if (isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else {
return data[idx_top];
}
}
public void print() {
for (int i = size() - 1; i >= 0; i--)
System.out.println(data[i]);
}
}
public class test {
public static void main(String[] args) {
StackSimple s = new StackSimple(3);// error shows here
s.push("books");
s.push("something");
s.push("200");
s.print();
System.out.println("Size=" + s.size());
}
}
I have basic understanding of how to apply Mockito framework.
But when it comes to some real time scenarios I failed to write tests in Isolation(by Mocking the dependent classes).
Can you help me to write Unit test for PriorityQueuePrinter class by Mocking PriorityQueue Implementation(BinaryMaxHeap.java).
I wrote testPriorityQueue() with BinaryMaxHeap object, in this case my test becomes success but I want to achieve the same to mock BinaryMaxHeap so that my test will be Isolate. I think I have to set method behaviours also in my test method.
In short, Priority Queue is the Implementation for BinaryHeapTree and Printer class uses Priority Queue.
Below are the code classes.
public interface PriorityQueue<T extends Comparable<T>> {
int size();
void insert(T element);
T popMax();
}
public class BinaryMaxHeap<T extends Comparable<T>> implements PriorityQueue<T> {
private ArrayList<T> items;
public BinaryMaxHeap() {
items = new ArrayList<T>();
}
public int size() {
return items.size();
}
public void insert(T element) {
items.add(element);
shiftUp();
}
public T popMax() {
if (items.size() == 1) {
return items.remove(0);
}
T hold = items.get(0);
items.set(0, items.remove(items.size()-1));
shiftDown();
return hold;
}
/*
* place newly added element in correct position in binary tree
*/
private void shiftUp() {
int k = items.size() - 1;
while (k > 0) {
int p = (k-1) / 2; // get parent element index
T child = items.get(k);
T parent = items.get(p);
if (child.compareTo(parent) > 0) {
// parent and child are not in correct position, need to swap
items.set(k, parent);
items.set(p, child);
k = p;
} else {
break;
}
}
}
private void shiftDown() {
int k = 0;
int l = 2*k+1; // left leaf node
while (l < items.size()) {
int max = l; // assume left node as max element
int r = l+1; // right leaf node
if (r < items.size()) {
if (items.get(r).compareTo(items.get(l)) > 0) {
max++; // identify max element in leaf nodes
}
}
T parent = items.get(k);
T child = items.get(max);
if (parent.compareTo(child) < 0) {
// parent element is less than leaf node, need to swap it
T temp = items.get(k);
items.set(k, items.get(max));
items.set(max, temp);
k = max;
l = 2*k+1;
} else {
break;
}
}
}
}
public interface Printer {
public <T extends Comparable<T>> String asSortedString(T... values);
}
public class PriorityQueuePrinter implements Printer {
private PriorityQueue priorityQueue = null;
public <T extends Comparable<T>> PriorityQueuePrinter(PriorityQueue<T> priorityQueue) {
this.priorityQueue = priorityQueue;
}
public <T extends Comparable<T>> String asSortedString(T... values) {
//PriorityQueue<T> priorityQueue =
addElements(values);
//return getSortedElements();
return null;
}
private <T extends Comparable<T>> void addElements(T... values) {
//PriorityQueue<T> priorityQueue = new BinaryMaxHeap<T>();
for (T element : values) {
priorityQueue.insert(element);
}
//return priorityQueue;
}
public int size() {
return priorityQueue.size();
}
private String getSortedElements() {
StringBuilder sortedElements = new StringBuilder();
boolean isFirstElement = true;
while(priorityQueue.size() > 0) {
if (!isFirstElement) {
sortedElements.append(",");
}
isFirstElement = false;
sortedElements.append(priorityQueue.popMax());
}
return sortedElements.toString();
}
public static void main(String a[]) {
PriorityQueuePrinter p = new PriorityQueuePrinter(new BinaryMaxHeap<Integer>());
String sortedElements = p.asSortedString(1,4,6,3,2);
System.out.println(sortedElements);
}
}
Below is the sample test code tried but not able to complete.
public class PrinterTest {
#Mock
PriorityQueue<Integer> mockPriorityQueue; // mock object
PriorityQueue<Integer> priorityQueue;
#Test
public void testPriorityQueueWithMock() {
PriorityQueuePrinter printer = new PriorityQueuePrinter(mockPriorityQueue);
String s = printer.asSortedString(5,3,6);
assertEquals("6,5,3", s);
}
#Ignore
public void testPriorityQueue() {
priorityQueue = new BinaryMaxHeap<Integer>();
PriorityQueuePrinter printer = new PriorityQueuePrinter(priorityQueue);
String s = printer.asSortedString(5,3,6);
assertEquals("6,5,3", s);
}
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
#After
public void tearDown() throws Exception {
System.out.println("==tearDown==");
}
}
#Before
public void setUp() throws Exception {
//mockPriorityQueue = new BinaryMaxHeap<Integer>();
MockitoAnnotations.initMocks(this);
}
}
I am trying to build a simple generic class that uses generic objects in java. everything compiles fine, but when i run the code, it doesn't display the objects i passed to it.
Here is my code:
public class ListDriver {
public static void main(String[] args) {
List<String> glist = new List<String>(10);
glist.add("milk");
glist.add("eggs");
System.out.println("Grocery List" + glist.toString());
}
public class List<T> {
private T[] datastore;
private int size;
private int pos;
public List(int numElements) {
size = numElements;
pos = 0;
datastore = (T[]) new Object[size];
}
public void add(T element) {
datastore[pos] = element;
}
public String toString() {
String elements = "";
for (int i = 0; i < pos; ++i) {
elements += datastore[i] + "";
}
return elements;
}
}
}
You don't increment your pos variable, so you're always adding in the same place. Try
public void add(T element) {
datastore[pos++] = element;
}
Your add method always replaces the element in position 0 (zero). You forgot to increment pos (pos++;)
My binary tree looks pretty close to my class materials, but when I print to the console or check for contains(), any adds I'm doing aren't registered.
I don't have a great understanding of static and the debugger is giving me a hint about making a static reference to non-static variable overallRoot, but everything compiles without error or warning in eclipse.
public class BSTSimpleSet<E extends Comparable<E>> implements SimpleSet<E> {
private GTNode<E> overallRoot;
private int size;
public static void main(String[] args) {
BSTSimpleSet<Integer> main = new BSTSimpleSet<Integer>(2);
main.toString();
main.add(3);
main.toString();
main.add(4);
main.toString();
main.add(5);
main.toString();
System.out.print(main.contains(3));
}
public BSTSimpleSet() {
size = 0;
}
public BSTSimpleSet(E input) {
overallRoot = new GTNode<E>(input);
size = 1;
}
public boolean add(E e) {
return add(e, overallRoot);
}
private boolean add(E e, GTNode<E> root) {
if (root == null) {
root = new GTNode<E>(e);
size++;
return true;
} else {
int compare = e.compareTo(root.data);
if (compare == 0) {
return false;
} else if (compare < 0) {
return add(e, root.left);
} else {
return add(e, root.right);
}
}
}
public void clear() {
overallRoot = null;
}
public boolean contains(E e) {
return contains(e, overallRoot);
}
private boolean contains(E e, GTNode<E> root) {
if (root == null) {
return false;
} else {
int compare = e.compareTo(root.data);
if (compare == 0) {
return true;
} else if (compare < 0) {
return contains(e, root.left);
} else {
return contains(e, root.right);
}
}
}
public boolean isEmpty() {
if (overallRoot == null) {
return false;
} else {
return true;
}
}
public int size() {
return size;
}
public String toString() {
this.toString(overallRoot, 0);
return null;
}
private void toString(GTNode<E> root, int level) {
if (root != null) {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println(root.data);
toString(root.left, level + 1);
toString(root.right, level + 1);
} else {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println("_");
}
}
private static class GTNode<E extends Comparable<E>> {
public E data;
public GTNode<E> left;
public GTNode<E> right;
public GTNode(E input) {
this(input, null, null);
}
public GTNode(E input, GTNode<E> lNode, GTNode<E> rNode) {
data = input;
left = lNode;
right = rNode;
}
}
}
This code does absolutely nothing.
private boolean add(E e, GTNode<E> root) {
if (root == null) {
root = new GTNode<E>(e);
size++;
return true;
}
...
Java passes in the Object Reference to a method. If you change the Reference, that will not
be propagated back to the calling method. If you change what the Reference refers to
that will be propagated back.
eg
// arrays behave the same way so using them to illustrate.
public void callMethods(){
int[] array = new int[1];
array[0] = 0;
doesNotChange(array);
System.out.println(array[0]);// will print 0
doesAChange(array);
System.out.println(array[0]);// will print 1
}
public void doesNotChange(int[] myArray){
myArray = new int[1];
myArray[0] = 1;
}
public void doesAChange(int[] myArray){
myArray[0] = 1;
}
To avoid these sorts of things I recommend always setting method parameters final.
The GTNode class shouldn't be static. Static classes are classes with only static methods, which means they don't have to be instantiated. The prototypical example of this is the java.lang.Math class: You don't need to call something like Math m = new Math(); m.cos(); to get the cosine, you just call Math.cos(). Since you're creating multiple instances of the GTNode class, make it non-static and you should be good.
This is an offshoot of these two questions: 1, 2.
I'd like to implement type-safe data structures in Java that prevent nonsensical operations. For example, if the compiler knows I have an instance of an empty stack, it shouldn't allow me to call pop on the empty stack.
As an example, how would I implement such a (generic) stack in Java?
See below Java implementation based on .net code from stakx's question.
If a client tries to pop too far, the compiler will issue an undefined method error. For example, issuing calls like:
new EmptyStack<Integer>().push(1).pop().getTop()
will result in an undefined method error on the call to getTop().
class GenericStack {
#Test public void test() {
final IStack<Integer> stack = new EmptyStack<Integer>();
assertEquals(new Integer(1), stack.push(1).getTop());
assertEquals(new Integer(2), stack.push(1).push(2).getTop());
assertEquals(new Integer(1), stack.push(1).push(2).pop().getTop());
}
interface IStack<T> {
INonEmptyStack<T, ? extends IStack<T>> push(T x);
}
interface IEmptyStack<T> extends IStack<T>
{
#Override INonEmptyStack<T, IEmptyStack<T>> push(T x);
}
interface INonEmptyStack<T, TStackBeneath extends IStack<T>>
extends IStack<T>
{
T getTop();
TStackBeneath pop();
#Override INonEmptyStack<T, INonEmptyStack<T, TStackBeneath>>
push(T x);
}
class EmptyStack<T> implements IEmptyStack<T> {
#Override public INonEmptyStack<T, IEmptyStack<T>> push(T x) {
return new NonEmptyStack<T, IEmptyStack<T>>(x, this);
}
}
class NonEmptyStack<T, TStackBeneath extends IStack<T>> extends Object
implements INonEmptyStack<T, TStackBeneath> {
private final TStackBeneath stackBeneathTop;
private final T top;
NonEmptyStack(T top, TStackBeneath stackBeneathTop) {
this.top = top;
this.stackBeneathTop = stackBeneathTop;
}
#Override public T getTop() {
return top;
}
#Override public TStackBeneath pop() {
return stackBeneathTop;
}
#Override public INonEmptyStack<T, INonEmptyStack<T, TStackBeneath>>
push(T x) {
return
new NonEmptyStack<T, INonEmptyStack<T, TStackBeneath>>(x, this);
}
}
// The following client code at the request of #TacticalCoder demonstrates
// some of the benefits (and limitations) of this implementation.
#Test public void testRandomPopper() {
IStack<?> stack = randomPopper(new EmptyStack<Integer>(), 20);
// This assertion will fail 1 out of .3^20 runs
assertTrue(stack instanceof INonEmptyStack<?,?>);
assertFalse(stack instanceof IEmptyStack<?>);
}
public IStack<Integer> randomPopper(IStack<Integer> s, final int N) {
IStack<Integer> stack;
if(N<1)
return s;
stack = s.Push(1);
for (int i = 1; i < N; i++) {
INonEmptyStack<Integer,?> tStack = stack.Push(i+1);
if(Math.random()<0.3) {
stack = tStack.Pop();
} else {
stack = tStack;
}
}
return stack;
}
#Test public void testDrainStack() {
IStack<Integer> stack = randomPopper(new EmptyStack<Integer>(), 20);
IStack<?> maybeEmptyStack = drainStack(stack);
assertTrue(maybeEmptyStack instanceof IEmptyStack);
IEmptyStack<?> definitelyEmptyStack = (IEmptyStack<?>) maybeEmptyStack;
assertTrue(definitelyEmptyStack instanceof IEmptyStack<?>);
}
#Test public void testCastNonEmptyStackToEmptyStack() {
IStack<Integer> stack = randomPopper(new EmptyStack<Integer>(), 20);
IStack<?> maybeEmptyStack = stack;
assertFalse(maybeEmptyStack instanceof IEmptyStack);
// Below cast should issue warning! Doesn't and issues runtime error.
IEmptyStack<?> definitelyEmptyStack = (IEmptyStack<?>) maybeEmptyStack;
assertFalse(definitelyEmptyStack instanceof IEmptyStack<?>);
}
public IStack<?> drainStack(IStack<?> stack) {
for (;stack instanceof INonEmptyStack<?,?>;)
stack = ((INonEmptyStack<?,?>) stack).Pop();
return stack;
}
}