Is this stack or stack emulation? - java

package java.util;
public
class Stack<E> extends Vector<E> {
public Stack() {
}
public E push(E item) {
addElement(item);
return item;
}
public synchronized E pop() {
E obj;
int len = size();
obj = peek();
removeElementAt(len - 1);
return obj;
}
public synchronized E peek() {
int len = size();
if (len == 0)
throw new EmptyStackException();
return elementAt(len - 1);
}
public synchronized int search(Object o) {
int i = lastIndexOf(o);
if (i >= 0) {
return size() - i;
}
return -1;
}
private static final long serialVersionUID = 1224463164541339165L;
}
Above is the java source code for stack.
I realized that it is only emulating a stack and not a real one.So my questions are
Am I right in saying that this is just an imitation of Stack and not the real one?
If I can say the above and I want to build it from scratch,how would I do it?(arrays of fixed size or arraylist which in turn uses list(single/double linked)?)

There is no "real Stack", a stack is just an idea, a so-called abstract data type. It supports two operations, push and pop, and the order of elements is defined to be last-in first-out (LIFO). In addition to java.util.Stack (based on Vector, which is array-based), you also have java.util.LinkedList (a doubly-linked list), which also supports stack operations, so it's also a stack as much as the other one.. There are several other implementations, for example all implementations of java.util.Deque.
You can do it from scratch in a number of ways, each has their own trade-offs. Your question is not defined enough for a good answer.

Related

Understanding an array with cache size elements

I am looking at a part of code that is used for an IDA* search. When a node is expanded, its child states are then put into the StateCache datastructure, which is a stack as far as I can tell. My question is this: is there any reason one would choose to set the max size of an array to a particular value? The cache data member has a number of elements equal to 10*1024, which seems to me that the cache data member is supposed to only store up to 10 KB (?) of elements, but I am really not sure. What would be the justification for the10*1024 number? Note that I have found this and this stack overflow posts that discuss cache hit/miss w.r.t row-major vs. column-major access of arrays, but these don't answer my question. Also, this code had no comments, otherwise I would've included more.
public class StateCache {
public static final int MAX_CACHE_SIZE = 10 * 1024;
int size;
State[] cache;
public StateCache() {
size = 0;
cache = new State[MAX_CACHE_SIZE];
}
// push and pop operations
public State get(State original) {
if (size > 0) {
size--;
State result = cache[size];
result.init(original);
return result;
} else {
return new State(original);
}
}
public void put(State[] children) {
for (State child: children) {
if (child == null) {
return;
}
if (size >= MAX_CACHE_SIZE) {
return;
}
cache[size] = child;
size++;
}
}
}

Efficient way to save last X amount of integers [duplicate]

A very simple & quick question on Java libraries: is there a ready-made class that implements a Queue with a fixed maximum size - i.e. it always allows addition of elements, but it will silently remove head elements to accomodate space for newly added elements.
Of course, it's trivial to implement it manually:
import java.util.LinkedList;
public class LimitedQueue<E> extends LinkedList<E> {
private int limit;
public LimitedQueue(int limit) {
this.limit = limit;
}
#Override
public boolean add(E o) {
super.add(o);
while (size() > limit) { super.remove(); }
return true;
}
}
As far as I see, there's no standard implementation in Java stdlibs, but may be there's one in Apache Commons or something like that?
Apache commons collections 4 has a CircularFifoQueue<> which is what you are looking for. Quoting the javadoc:
CircularFifoQueue is a first-in first-out queue with a fixed size that replaces its oldest element if full.
import java.util.Queue;
import org.apache.commons.collections4.queue.CircularFifoQueue;
Queue<Integer> fifo = new CircularFifoQueue<Integer>(2);
fifo.add(1);
fifo.add(2);
fifo.add(3);
System.out.println(fifo);
// Observe the result:
// [2, 3]
If you are using an older version of the Apache commons collections (3.x), you can use the CircularFifoBuffer which is basically the same thing without generics.
Update: updated answer following release of commons collections version 4 that supports generics.
Guava now has an EvictingQueue, a non-blocking queue which automatically evicts elements from the head of the queue when attempting to add new elements onto the queue and it is full.
import java.util.Queue;
import com.google.common.collect.EvictingQueue;
Queue<Integer> fifo = EvictingQueue.create(2);
fifo.add(1);
fifo.add(2);
fifo.add(3);
System.out.println(fifo);
// Observe the result:
// [2, 3]
I like #FractalizeR solution. But I would in addition keep and return the value from super.add(o)!
public class LimitedQueue<E> extends LinkedList<E> {
private int limit;
public LimitedQueue(int limit) {
this.limit = limit;
}
#Override
public boolean add(E o) {
boolean added = super.add(o);
while (added && size() > limit) {
super.remove();
}
return added;
}
}
Use composition not extends (yes I mean extends, as in a reference to the extends keyword in java and yes this is inheritance). Composition is superier because it completely shields your implementation, allowing you to change the implementation without impacting the users of your class.
I recommend trying something like this (I'm typing directly into this window, so buyer beware of syntax errors):
public LimitedSizeQueue implements Queue
{
private int maxSize;
private LinkedList storageArea;
public LimitedSizeQueue(final int maxSize)
{
this.maxSize = maxSize;
storageArea = new LinkedList();
}
public boolean offer(ElementType element)
{
if (storageArea.size() < maxSize)
{
storageArea.addFirst(element);
}
else
{
... remove last element;
storageArea.addFirst(element);
}
}
... the rest of this class
A better option (based on the answer by Asaf) might be to wrap the Apache Collections CircularFifoBuffer with a generic class. For example:
public LimitedSizeQueue<ElementType> implements Queue<ElementType>
{
private int maxSize;
private CircularFifoBuffer storageArea;
public LimitedSizeQueue(final int maxSize)
{
if (maxSize > 0)
{
this.maxSize = maxSize;
storateArea = new CircularFifoBuffer(maxSize);
}
else
{
throw new IllegalArgumentException("blah blah blah");
}
}
... implement the Queue interface using the CircularFifoBuffer class
}
The only thing I know that has limited space is the BlockingQueue interface (which is e.g. implemented by the ArrayBlockingQueue class) - but they do not remove the first element if filled, but instead block the put operation until space is free (removed by other thread).
To my knowledge your trivial implementation is the easiest way to get such an behaviour.
You can use a MinMaxPriorityQueue from Google Guava, from the javadoc:
A min-max priority queue can be configured with a maximum size. If so, each time the size of the queue exceeds that value, the queue automatically removes its greatest element according to its comparator (which might be the element that was just added). This is different from conventional bounded queues, which either block or reject new elements when full.
An LRUMap is another possibility, also from Apache Commons.
http://commons.apache.org/collections/apidocs/org/apache/commons/collections/map/LRUMap.html
Ok I'll share this option. This is a pretty performant option - it uses an array internally - and reuses entries. It's thread safe - and you can retrieve the contents as a List.
static class FixedSizeCircularReference<T> {
T[] entries
FixedSizeCircularReference(int size) {
this.entries = new Object[size] as T[]
this.size = size
}
int cur = 0
int size
synchronized void add(T entry) {
entries[cur++] = entry
if (cur >= size) {
cur = 0
}
}
List<T> asList() {
int c = cur
int s = size
T[] e = entries.collect() as T[]
List<T> list = new ArrayList<>()
int oldest = (c == s - 1) ? 0 : c
for (int i = 0; i < e.length; i++) {
def entry = e[oldest + i < s ? oldest + i : oldest + i - s]
if (entry) list.add(entry)
}
return list
}
}
public class ArrayLimitedQueue<E> extends ArrayDeque<E> {
private int limit;
public ArrayLimitedQueue(int limit) {
super(limit + 1);
this.limit = limit;
}
#Override
public boolean add(E o) {
boolean added = super.add(o);
while (added && size() > limit) {
super.remove();
}
return added;
}
#Override
public void addLast(E e) {
super.addLast(e);
while (size() > limit) {
super.removeLast();
}
}
#Override
public boolean offerLast(E e) {
boolean added = super.offerLast(e);
while (added && size() > limit) {
super.pollLast();
}
return added;
}
}

Deep copying Generics in Java

I have a programming assignment to make a generic stack in Java and I need to make a deep copy of newNode T. I don't know how to make a method deep Copy that can access its self and output i'`s deep copy. So far, I have this:
public class Stack<T>
{
private T[] data;
private int top;
private int size;
public Stack( )
{ top = -1;
size = 100;
data = (T[])new Object[100];
}
public Stack(int n)
{ top = -1;
size = n;
data = (T[])new Object[n];
}
public boolean push(T newNode)
{ if(top == size-1)
return false; // ** overflow error **
else
{ top = top +1;
data[top] = newNode.deepCopy();
return true; // push operation successful
}
}
public T pop( )
{ int topLocation;
if(top == -1)
return null; // ** underflow error **
else
{ topLocation = top;
top = top -1;
return data[topLocation];
}
}
public void showAll( )
{ for(int i = top; i >= 0; i--)
System.out.println(data[i].toString());
}
}
How can I make the deep copy of newNode. I'm pretty sure I need an interface for the method but past that I`m lost.
Perhaps the most general and straight forward solution would consist in asking the using code to provide the deep-copying routine at construction:
public class Stack<T> {
...
private final Function<T, T> elementCopier;
public Stack<T>(Function<T, T> elementCopier) {
// make sure thy are not passing you a null copier:
this.elementCopier = Objects.requiresNonNull(elementCopier);
...
}
...
public boolean push(T element) {
...
data[top] = elementCopier.apply(element);
...
}
...
}
So for example for a cloneable class type where .clone() is in fact a deepCopy the user code would be like:
Stack<MyElemClz> stack = new Stack<>(x -> x.clone());
// or:
Stack<MyElemClz> stack = new Stack<>(MyElemClz::clone);
...
MyElemClaz elem = ...;
...
stack.push(elem);
If the type is an constant simple object like and String there is no need for clonning, in that case the user would indicate identity lambda x -> x as
the copier:
Stack<String> stack = new Stack<>(x -> x)
If the user insists in making a copy even when the class is a constant you can force it:
Stack<String> stack = new Stack<>(x -> new String(x))
// or
Stack<String> stack = new Stack<>(String::new)
One can use an ObjectOutputStream/ObjectInputStream to make a deep copy.
One would then not store an Object (a reference to changeable fields), but the serialized bytes in the stack.
On to it.
An ObjectOutputStream does a deep copy.
If you want to go with an interface, or you don't like Valentin's approach, you could do this:
interface Copiable<T> {
T deepCopy();
}
public class Stack<T extends Copiable<T>> {
...
}
and then implement the deepCopy method to objects that you put in your stack, i.e.
class A implements Copiable<A> {
#Override
public A deepCopy() {
// ... your copy code here
}
}
Stack<A> stack = new Stack<>();
etc.

I'm not sure how to make this stack implementation dynamic

First of all, I apologise if this is a really obvious question or if I'm not looking at it correctly.
I've been instructed to "extend the stack to be dynamic". I've been given specific instructions on how to do this, namely:
Make a new array tmp of twice the size of the current array
Copy all elements the current array (called S in the lecture notes) into tmp
Set S = tmp;
The block of code which should do this is to be placed into the push() method, replacing the exception throw section.
The problem is, I have no idea what kind of array I should be using (generics have only recently introduced to me and I don't quite understand them as much as I think I should).
Is there something obvious I'm missing or do I just not understand this properly?
I didn't write the majority of this code, only the pop(), push() and top() methods.
public class ArrayStack<E> implements Stack<E> {
private E[] S;
private int top;
private int capacity;
private static int DEFAULT_SIZE = 100;
public ArrayStack(int size){
capacity = size;
S = (E[]) new Object[size];
top = -1;
}
public ArrayStack(){
this(DEFAULT_SIZE);
}
public E pop() throws StackException{
if(isEmpty())
throw new StackException("stack is empty");
return S[top--];
}
public void push(E e) throws StackException{
if (size() == capacity)
throw new StackException("Stack is full");
S[++top] = e;
}
public E top() throws StackException{
if(isEmpty())
throw new StackException("Stack is empty");
return S[top];
}
Looking at your code, it appears that the array should be of E objects.
Using Java Generics, you can create this array with (E[]) new Object[2 * initial_size]
The instructions want you to look at the code segment below in push
if (size() == capacity)
throw new StackException("Stack is full");
and without giving too much away as this is an assignment to do
if (size() == capacity)
Make a new array tmp of twice the size of the current array
Copy all elements the current array (called S in the lecture notes) into tmp
S = tmp;

Comparison operators in generic heap

For my data structures class our homework is to create a generic heap ADT. In the siftUp() method I need to do comparison and if the parent is smaller I need to do a swap. The problem I am having is that the comparison operators are not valid on generic types. I believe I need to use the Comparable interface but from what I read it’s not a good idea to use with Arrays. I have also search this site and I have found good information that relates to this post none of them helped me find the solution
I removed some of the code that wasn’t relevant
Thanks
public class HeapQueue<E> implements Cloneable {
private int highest;
private Integer manyItems;
private E[] data;
public HeapQueue(int a_highest) {
data = (E[]) new Object[10];
highest = a_highest;
}
public void add(E item, int priority) {
// check to see is priority value is within range
if(priority < 0 || priority > highest) {
throw new IllegalArgumentException
("Priority value is out of range: " + priority);
}
// increase the heaps capacity if array is out of space
if(manyItems == data.length)
ensureCapacity();
manyItems++;
data[manyItems - 1] = item;
siftUp(manyItems - 1);
}
private void siftUp(int nodeIndex) {
int parentIndex;
E tmp;
if (nodeIndex != 0) {
parentIndex = parent(nodeIndex);
if (data[parentIndex] < data[nodeIndex]) { <-- problem ****
tmp = data[parentIndex];
data[parentIndex] = data[nodeIndex];
data[nodeIndex] = tmp;
siftUp(parentIndex);
}
}
}
private int parent(int nodeIndex) {
return (nodeIndex - 1) / 2;
}
}
Technically you're using the comparable interface on on item, not an array. One item in the array specifically. I think the best solution here is to accept, in the constructor, a Comparator that the user can pass to compare his generic objects.
Comparator<E> comparator;
public HeapQueue(int a_highest, Comparator<E> compare)
{
this.comparator = compare;
Then, you would store that comparator in a member function and use
if (comparator.compare(data[parentIndex],data[nodeIndex]) < 0)
In place of the less than operator.
If I am reading this right, E simply needs to extend Comparable and then your problem line becomes...
if (data[parentIndex].compareTo(ata[nodeIndex]) < 0)
This is not breaking any bet-practice rules that I know of.

Categories

Resources