https://docs.oracle.com/javase/7/docs/api/java/util/Deque.html
I am learning about to how use this object.
boolean add(E e)
Inserts the specified element into the queue represented by this deque
(in other words, at the tail of this deque) if it is possible to do so
immediately without violating capacity restrictions, returning true
upon success and throwing an IllegalStateException if no space is
currently available.
I am confused on 'if no space is currently available.' I don't see anything where you set the size, does it mean No space as in, no JVM?
I am looking into how to make a Deque that holds 5 values and I want to add one and remove the oldest when it is at 5.
I hope this makes sense, if not please ask me to elaborate and I will.
Thanks a lot SOF community!
This is how I would do it with a Deque - it's simple but I think it addresses the problem you are trying to solve.
public class DequeExample {
Deque<Integer> deque = new ArrayDeque<>();
public static void main(String[] args) {
DequeExample dequeExample = new DequeExample();
// adding elements
for( int idx = 0; idx < 9; idx++){
dequeExample.addNewest(idx);
}
}
private void addNewest(int newest){
if(deque.size() == 5){
System.out.println("Queue at capacity, removing element before adding more.");
Integer e = deque.removeLast();
System.out.println("Removed: " + e);
}
deque.push(newest);
System.out.println("Added: " + newest );
System.out.println(deque);
}
}
How to use Deque (and then its just about wrapping this to methods you wish to support with few if statements):
Deque<String> deq = new LinkedList<>(); //to have a fixed size, use ArrayDeque<E>
deq.addFirst("a");
System.out.println(deq.peekFirst()); //a - just take a look, do not remove
deq.addFirst("b");
System.out.println(deq.peekFirst()); //b
System.out.println(deq.peekLast()); //a
deq.addLast("c");
System.out.println(deq.peekLast()); //c
deq.add("d");
System.out.println(deq.peekLast()); //d
System.out.println(deq.pollLast()); //d - return and remove
System.out.println(deq.pollLast()); //c
If you want to have some kind of circular buffer, you may want to use this Apache Commons collection instead - CircularFifoBuffer
Related
I believe I just correctly completed the following assignment:
Implement a heap based priority queue class using the vector representation, containing characters.
My program compiles and when implemented for the remainder of the assignment I achieved all of the desired outputs. My question is whether I actually implemented the heap correctly. My teacher identified three key methods for a heap-based queue: downheap, upheap, and extractMin.
public static void upheap(int j)
{
int p = parent(j);
if(heap.get(j) < heap.get(p)) { swap(j,p); }
if (j == 0) return;
upheap(p);
}
public static char extractRoot()
{
if (heap.size() == 0)
return 0;
char root = heap.get(0);
heap.set(0,heap.get(heap.size() - 1));
heap.remove(heap.size() - 1);
downheap(0);
return root;
}
public static void downheap(int j)
{
if(hasLeft(j))
{
int smallerIndex = left(j);
if(hasRight(j) && heap.get(right(j)) < heap.get(left(j)))
smallerIndex = right(j);
if(heap.get(j) > heap.get(smallerIndex))
{
swap(j, smallerIndex);
}
upheap(j);
downheap(smallerIndex);
}
}
However, I feel like my downheap function is just piggybacking off of upheap, and actually entirely unnecessary. I have the function:
public static void add(char c)
{
heap.add(c);
upheap(heap.size() - 1);
}
(where heap is an ArrayList) and that automatically makes sure that every new entry follows the heap-order property. I never actually end up using downheap to sort anything - so is there any point to even keep it in the class? When would I use it?
If anyone wants to see the rest of the methods in the class I'll post
Actually you can remove the call to upheap() in your downheap() method.
As you know the root in a priority queue heap is highest priority element.
The downheap method comes into picture only when the highest priority element is removed i.e. the root element is swapped with the last element. In your case the extractRoot() method. Once you extractRoot() all the the other elements in the heap would satisfy the heap property except the one on root.
Also when you are moving the root element down you are swapping with the smaller value i.e swap(j, smallerIndex). Hence there would never be a case when you would need to move an element up the heap in case of downheap().
To answer your question, when you call add() downHeap() is useless but when you call extractMin() downheap() is necessary.
Heap Image
So I tried to implement a stack with just one queue and it appears to work, but I'm not sure if there's something wrong with it since most of the solutions I've seen online use two queues. Can anyone tell if me if there are problems with my implementation?
public class MyStack<T> {
/**
* #param args
*/
private Queue<T> q = new LinkedList<T>();
public MyStack(){
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MyStack<String> s = new MyStack<String>();
s.push("1");
s.push("2");
s.push("3");
s.push("4");
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
}
public void push(T s){
q.offer(s);
}
public T pop(){
int n = q.size();
for(int i = 0; i < n-1; i++){
q.offer(q.poll());
}
return q.poll();
}
}
Output:
4
3
2
1
null
Your solution is inefficient because you have to loop through the whole stack every time you pop something from it. (Effectively you have to traverse the whole linked list, before removing the element that was at the end.)
Edit: Java's linked list is doubly linked anyway, so this is entirely pointless.
You should use either a Stack or a Deque or even a LinkedList.
Implementing your own is just ... pointless. Unless of course (as #bas suggests) you are doing a course on data structures in which case you should go Commando and implement your own structure from scratch. Using another structure because it is nearly like the one you are trying to make is like using a hammer with screws.
If you really need to implement something yourself something like this should work:
public class Stack<T> {
private Entry top = null;
private class Entry {
final Entry up;
final T it;
public Entry(Entry up, T it) {
this.up = up;
this.it = it;
}
}
public void push ( T it ) {
top = new Entry(top, it);
}
public T pop () {
if ( top == null ) {
throw new EmptyStackException();
}
T it = top.it;
top = top.up;
return it;
}
}
NB: This may not be thread safe.
There is absolutely no reason a stack should use two queues. As a matter of fact, it only needs to keep track of one top-node that references the nodes below it.
The code seems to work, but as nachokk said, this is not the site for code review. This site is ment if you run into errors and require assistance.
You must use two queues ONLY when you have basic queues operations, like enqueue and dequeue. When you can use other methods, especially iterating over queue, you can do it with only one queue, like you did.
I'm working on sorted Queues like a Priority Queue. I already did it with a List, and it already worked great. Now I'd like to do it with a array. But I have a little logical Problem with add a new Element and insert it into the sorted array.
The final output should be like that:
Priority: 5 Value: x
Priority: 4 Value: iso
.... (and so on)
So the Element with the highest Priorithy should be on index = 0.
I just don't know (and yes I know it's really simply to switch it, but I just can't do it :/) how to do it...
I already tried a few things but I'm stuck... :/ can please anyone help?
Here's my code:
public class Queue {
private QueueElem[] a;
public Queue(int capacity)
{
QueueElem[] tempQueue = new QueueElem[capacity];
a= tempQueue;
}
public void enqueue(int p, String v)
{
QueueElem neu = new QueueElem(p,v);
int i=0;
while(i<a.length)
{
if (a[i] == null)
{
a[i] = neu;
break;
}
i++;
}
}
public void writeQueue()
{
int i=0;
while((i< a.length) && (a[i] != null))
{
System.out.println("Priority: " + a[i].priority + " Value: " + a[i].value);
i++;
}
}
public static void main(String args[])
{
Queue neu = new Queue(10);
neu.enqueue(4,"iso");
neu.enqueue(2,"abc");
neu.enqueue(5,"x");
neu.enqueue(1,"abc");
neu.enqueue(4,"bap");
neu.enqueue(2,"xvf");
neu.enqueue(4,"buep");
}
}//end class Queue
class QueueElem {
int priority;
String value = new String();
public QueueElem(){ }
public QueueElem(int p, String v)
{
this.priority = p;
this.value = v;
}
public int getPrio()
{
return this.priority;
}
public String getValue()
{
return this.value;
}
}
It would be better if you interpreted your array as a max-heap. That is the typical way to implement priority queue.
What you're looking for, if you're trying to maintain a sorted array for your priority queue, is to implement insertion sort (sort of; you don't have an unsorted array to start with. You have an empty array that you simply add to, while maintaining a sorted order). Every time you insert a new element, you will iterate through the array to find the correct spot and then insert it there, after shifting the elment currently at that spot, and everything after it one spot down. Note that this is not as performant as implementing this using a heap, since at worst you have O(n) performance every time you insert, whereas with a heap you have O(logn).
I don't understand why anyone would want to work with raw arrays... especially now that you have implemented it with a List.
If you want to see how to insert an element in a raw array, look in the code of ArrayList, since underneath it uses a raw array. You'll have to move all the elements to right of the insertion point, which you could copy in a loop, or by using System.arraycopy(). But the nastiest part is that you will likely have to create a new array since the array size increases by one when you add an element (it depends if you are using an array that has exactly the size of your data, or a larger array, as is done in ArrayList).
Yeah, it's a homework question, so givemetehkodezplsthx! :)
Anyway, here's what I need to do:
I need to have a class which will have among its attributes array of objects of another class. The proper way to do this in my opinion would be to use something like LinkedList, Vector or similar. Unfortunately, last time I did that, I got fire and brimstone from my professor, because according to his belief I was using advanced stuff without understanding basics.
Now next obvious solution would be to create array with fixed number of elements and add checks to get and set which will see if the array is full. If it is full, they'd create new bigger array, copy older array's data to the new array and return the new array to the caller. If it's mostly empty, they'd create new smaller array and move data from old array to new. To me this looks a bit stupid. For my homework, there probably won't be more that 3 elements in an array, but I'd like to make a scalable solution without manually calculating statistics about how often is array filled, what is the average number of new elements added, then using results of calculation to calculate number of elements in new array and so on.
By the way, there is no need to remove elements from the middle of the array.
Any tips?
class test {
private Object[] objects;
private int size;
public test() {
objects = new Object[10];
size = 0;
}
public void push(Object o) {
if (objects.length == size) {
throw new RuntimeException("This wouldn't happen if I didn't have to reinvent the wheel");
}
objects[size] = o;
size++;
}
public Object pop() {
size--;
Object o = objects[size];
objects[size] = null;
return o;
}
}
Just kidding. I think you're best bet is to implement your own linked list and then use that in your class. Something like:
class Element {
Object val;
Element next;
Element prev;
public Element(Object val, Element next, Element prev) {
this.val = val;
this.next = next;
this.prev = prev;
}
}
class LinkedList {
Element head;
Element tail;
public void add(Object o) {
Element el = new Element(o, null, tail);
tail.next = el;
}
public Object remove() {
Element o = tail;
tail = o.prev;
tail.next = null;
return o.val;
}
}
One thing you will want to do is when you need to grow the size of your array create an array that is twice the size of the old array. Likewise, if you need to shrink the size of hte array, only do it once the array is half full.
This will make it so you have to do far less array copies.
Doing this will make it necessary to keep a variable that keeps track of the actual size of the array because the length of the array will not accurately represent the actual size.
To copy an existing array into a smaller or larger one, you may find System#arrayCopy() useful.
Kickoff example:
Object[] originalArray = new Object[3];
// ...
Object[] resizedArray = new Object[originalArray.length + 2]; // Grow with 2.
System.arrayCopy(originalArray, 0, resizedArray, 0, originalArray.length);
This will copy the items over the entire length of originalArray into the beginning of resizedArray. The 2 slots at end of resizedArray are still null so that you can use it for other items.
This must get you started. Good luck :)
Is it for a data structures class ? Sounds like your professor expects you to implement your own Linked List data structure or something similar instead of using the one Java provides. Google and your text book(s) are your friend.
If I recall correctly, the ArrayList class works by having a fixed size array (with an initial capacity of whatever you set) that resizes in pretty much the way you described when it's full.
You could use a linked list, though by the sounds of it your professor wants you to program this stuff by yourself, so create your own class demonstrating you know how it works?
i think its really easy way :p which we cant do in C but can do in java
package javaapplication21;
import java.util.Scanner;
public class JavaApplication21 {
public static void main(String[] args) {
int a;
Scanner obj=new Scanner(System.in);
System.out.print("Enter array size=");
a=obj.nextInt();
int b[]=new int[a];
for(int i=0;i<b.length;i++){
System.out.println(b[i]+i);
}
}
}
I need to use a FIFO structure in my application. It needs to have at most 5 elements.
I'd like to have something easy to use (I don't care for concurrency) that implements the Collection interface.
I've tried the LinkedList, that seems to come from Queue, but it doesn't seem to allow me to set it's maximum capacity. It feels as if I just want at max 5 elements but try to add 20, it will just keep increasing in size to fit it. I'd like something that'd work the following way:
XQueue<Integer> queue = new XQueue<Integer>(5); //where 5 is the maximum number of elements I want in my queue.
for (int i = 0; i < 10; ++i) {
queue.offer(i);
}
for (int i = 0; i < 5; ++i) {
System.out.println(queue.poll());
}
That'd print:
5
6
7
8
9
Thanks
Create your own subclass of the one you want, and override the add method so that it
checks if the new object will fit, and fails if not
calls super.add()
(and the constructors).
If you want it to block when inserting if full, it is a different matter.
I haven't seen any limitation like that in the API. You can use ArrayList by changing the behavior of the add method with anonymous class feature:
new ArrayList<Object>(){
public boolean add(Object o){ /*...*/ }
}
Looks like what you want is a limited size FIFO structure, that evicts oldest items when new ones are added. I recommend a solution based on a cyclic array implementation, where you should track the index of the queue tail and queue head, and increase them (in cyclic manner) as needed.
EDIT:
Here is my implementation (note that it IS a Collection). It works fine with your test scenario.
public class XQueue <T> extends AbstractQueue<T>{
private T[] arr;
private int headPos;
private int tailPos;
private int size;
#SuppressWarnings("unchecked")
public XQueue(int n){
arr = (T[]) new Object[n];
}
private int nextPos(int pos){
return (pos + 1) % arr.length;
}
#Override
public T peek() {
if (size == 0)
return null;
return arr[headPos];
}
public T poll(){
if (size == 0)
return null;
size--;
T res = arr[headPos];
headPos = nextPos(headPos);
return res;
}
#Override
public boolean offer(T e) {
if (size < arr.length)
size++;
else
if (headPos == tailPos)
headPos = nextPos(headPos);
arr[tailPos] = e;
tailPos = nextPos(tailPos);
return true;
}
#Override
public Iterator<T> iterator() {
return null; //TODO: Implement
}
#Override
public int size() {
return size;
}
}
Perhaps an ArrayBlockingQueue might do the trick. Look here. Try something like this:
BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(5);
for (int i = 0; i < 10; i++) {
while (!queue.offer(i)) {
queue.poll();
}
}
for (int i = 0; i < 5; i++) {
System.out.println(queue.poll());
}
You have three choices
1) Subclass an Abstract Collection
2) Limit the size to five and do the logic around the code where you are doing the insert.
3) Use LinkedListHashMap The removeEldestEntry(Map.Entry) method may be overridden to impose a policy for removing stale mappings automatically when new mappings are added to the map. (You would then use an Iterator to get the values - which will be returned in order of insertion)
Your best bet is #1 - It is real easy if you look at the link.
Did you have a look at the Apache Commons Collections library? The BoundedFifoBuffer should exactly meet your needs.
If I remember correctly, I've done exactly what you want using a LinkedList.
What you need to do is check the size of the List, if it's 5 and you want to add objects, just delete the first element and keep doing so if the size is 5.