How to create queue methods? - java

I have a project for a java training where I have to create a class that implements Queue interface and all its methods! After the implementation I need to create the bodies for all the methods but I'm not sure how. I can't use any implementation from Collection, such Arraylist, LinkedList etc. If I can't use that, where do I store all the elements? Can you give me an example for one method?
Thank you very much!

Well, you haven't given me enough information. I don't know what methods does Queue interface include and what you really need. However, I did create the following code with may or not help you.
public interface Queue<T> {
T getFirst();
T getLast();
T getMid();
T getIndex(int index);
}
public class Toilet<T> implements Queue {
private T[] list;
public Toilet(T... list) {
this.list = list;
}
public void setList(T[] list) {
this.list = list;
}
public T[] getList() {
return list;
}
#Override
public T getFirst() {
return list[0];
}
#Override
public T getLast() {
return list[list.length-1];
}
#Override
public T getMid() {
return list[list.length/2];
}
#Override
public T getIndex(int index) {
if (index >= 0 && index < list.length) return list[index];
throw new NullPointerException();
}
}

Related

How to print elements from generic array list, using iterator in Java

I'm working in a school project, where I want to implement the Iterator design pattern. I want to use generic arrays.
Container.java
public interface Container {
Iterator getIterator();
}
Iterator.java
public interface Iterator <T> {
boolean hasNext();
T next();
}
TransactionRepository.java
public class TransactionRepository<T> implements Container {
public TransactionRepository(){
userTransactions = new ArrayList<>();
}
public List<T> userTransactions;
#Override
public Iterator <T> getIterator() {
return new UserTransactions();
}
private T t;
public void add(T t) {
this.t = t;
}
public T get() {
return t;
}
private class UserTransactions implements Iterator <T> {
int index;
#Override
public boolean hasNext() {
return index < userTransactions.size();
}
#Override
public T next() {
if(this.hasNext())
return userTransactions.get(index);
return null;
}
}
}
In my other class, I add the elements to the list by first creating the TransactionRepository object like this: TransactionRepository<String> companyName = new TransactionRepository<String>();.
Then I add elements to the array with the add method companyName.add("CompanyName");. After that I want to print the array using Iterator, but It just won't print the elements. I have tried multiple variations, but none of them worked.
Iterator <String> stringIterator = companyName.getIterator();
while (stringIterator.hasNext()) {
System.out.println("Name : " + companyName.get());
}
With the current implementation List<T> userTransactions is never updated.
In this case userTransactions.size() in hasNext() method will always return 0 so the result of method will be false.
Moreover, you should use stringIterator.next() instead of companyName.get(). Since you implement your own iterator you don't want to use get() method at all.
There is also a need to update index counter variable after calling next() method.
#Override
public T next() {
if (this.hasNext())
return userTransactions.get(index++);
return null;
}
Change modifier on userTransactions to private final as it should be referenced just with iterator.
Code with proposed improvements:
public class TransactionRepository<T> implements Container {
public TransactionRepository() {
userTransactions = new ArrayList<>();
}
public List<T> userTransactions;
#Override
public Iterator<T> getIterator() {
return new UserTransactions();
}
public void add(T t) {
userTransactions.add(t);
}
private class UserTransactions implements Iterator<T> {
int index;
#Override
public boolean hasNext() {
return index < userTransactions.size();
}
#Override
public T next() {
if (this.hasNext()) {
return userTransactions.get(index++);
}
return null;
}
}
}
It seems that you are never adding elements to your userTransactions List on the add method
You add() method doesnt add anything to your list , it's just like a setter of the attribute t , you should use it to add elements to the list instead
public void add(T t) {
userTransactions.add(t);
}
There is also another problem , the index , your next() method gets the index element while you didnt initialise your index variable , i recommand you to do it in this way :
int index = 0 ;
...
public T next() {
if(this.hasNext())
int temp = index;
index++;
return userTransactions.get(temp);
return null;
}

Implementing an interface in an anonymous class as an iterator: type issue

I'm having an issue with a project I'm working on. One of the things that needs to happen is to create an inspector which returns an iterator which implements an interface, while using an anonymous class. The context is a filesystem and basically, the iterator just needs to return the content of the directory the iterator works on. So here's the code I got at the moment:
Directory class:
public class Directory {
...
public Iterator<DiskItem> iterator() {
return new DirectoryIterator() {
int cursor = 1;
int end = Directory.this.getNbItems();
public boolean hasNext() {
return this.cursor < end;
}
public DiskItem next(){
if(this.hasNext()) {
Directory.this.getItemAt(this.cursor++);
}
else
throw new NoSuchElementException();
}
#Override
public int getNbRemainingItems() {
return this.end - this.cursor;
}
#Override
public DiskItem getCurrentItem() throws IndexOutOfBoundsException {
return Directory.this.getItemAt(this.cursor);
}
#Override
public void advance() {
if(this.hasNext()) {
this.cursor++;
}
else
throw new NoSuchElementException();
}
#Override
public void reset() {
this.cursor = 1;
}
}
}
DirectoryIterator Interface:
public interface DirectoryIterator {
int getNbRemainingItems();
DiskItem getCurrentItem() throws IndexOutOfBoundsException;
void advance();
void reset();
}
The problem I'm having is getting the error
Type mismatch: cannot convert from new DirectoryIterator(){} to Iterator<DiskItem>
and that's probably because DirectoryIterator doesn't have the type Iterator, but because it's an interface, I cannot give it any type.
Anyone an idea on how to solve this?
Thanks in advance
A way to fix this problem would be to make DirectoryIterator extend Iterator<DiskItem>
Like this:
interface DirectoryIterator extend Iterator<DiskItem> {
...
}
This way DirectoryIterator is a subclass of Iterator<DiskItem> so using polymorphism we can return a DirectoryIterator as a Iterator<DiskItem>
Hope this helps, if this doesn't fix your problem be sure to leave a comment.

Right way to make my own collection in java

I'm trying to do my own collection class in java.
I need to find data by a key and also be able to iterate on it and get a element by his index, so i decide to make an encapsulation of the hashtable and the arraylist.
This is my code:
public class GeoCollection <T extends Geographic> implements Iterable<T>, Iterator<T>{
private Hashtable<String,T> data_table;
private ArrayList<T> data;
private int cursor = 0;
public GeoCollection(){
data = new ArrayList<>();
data_table = new Hashtable<>();
}
public void add(String key,T data){
this.data.add(data);
data_table.put(key,data);
}
public T get(int index){
if(index >= data.size())
throw new IndexOutOfBoundsException();
return data.get(index);
}
public T get(String v){
return data_table.get(v);
}
public T next() {
if( cursor == data.size())
throw new NoSuchElementException();
cursor++;
return data.get(cursor-1);
}
public T first(){
cursor = 0;
return data.get(cursor);
}
public boolean hasNext(){
return cursor < data.size();
}
public boolean remove(Person p) {
return data.remove(p);
}
//se implemeta el iterator
#Override
public Iterator<T> iterator() {
cursor = 0;
return this;
}
}
There's any need to implement list interface or something like that? Because i don't know if encapsulating the hashtable and the arraylist and implementing the basic operations in enough to call "Collection" this class.
I will be very thankful for any advice or correction of this code.
Thanks.
i think the best way to do this is implementing Collection
implements java.util.Collection<E>
that way you have to implement every method in the collection interface bt
making your class extending AbstractCollection extends AbstractCollection is much more easy since it does
all the nessessary things for us and only thing you have to worry about is
iterator() and size()

Allocation free game

My code is basically allocation free, however the GC runs every 30 seconds or so when at 60fps. Checking the app with DDMS for allocation shows there is ALOT of SimpleListIterator being allocated. There is also some stuff being allocated because i use Exchanger.
The SimpleListIterator comes from for each loops for (T obj : objs) {}. I was under the impression that the compilator/translator would optimize those to not use iterators for types that support it (I basically only use ArrayList) but that seems to not be the case.
How can I avoid allocating all these SimpleListIterators? One solution would be to switch to regular for loops for (int i = 0; i < size; ++i) {} but I like for each loops :(
Another way would be to extend ArrayList which returns an Iterator that is only allocated once.
A third way I hacked together is using a static helper function which returns a Collection which is reusing an Iterator. I hacked something like this together but the casting feels very hackish and unsafe. It should be thread safe though as I use ThreadLocal? See below:
public class FastIterator {
private static ThreadLocal<Holder> holders = new ThreadLocal<Holder>();
public static <T> Iterable<T> get(ArrayList<T> list) {
Holder cont = holders.get();
if (cont == null) {
cont = new Holder();
cont.collection = new DummyCollection<T>();
cont.it = new Iterator<T>();
holders.set(cont);
}
Iterator<T> it = (Iterator<T>) cont.it;
DummyCollection<T> collection = (DummyCollection<T>) cont.collection;
it.setList(list);
collection.setIterator(it);
return collection;
}
private FastIterator() {}
private static class Holder {
public DummyCollection<?> collection;
public Iterator<?> it;
}
private static class DummyCollection<T> implements Iterable {
private Iterator<?> it;
#Override
public java.util.Iterator<T> iterator() {
return (java.util.Iterator<T>) it;
}
public void setIterator(Iterator<?> it) {
this.it = it;
}
}
private static class Iterator<T> implements java.util.Iterator<T> {
private ArrayList<T> list;
private int size;
private int i;
#Override
public boolean hasNext() {
return i < size;
}
#Override
public T next() {
return list.get(i++);
}
#Override
public void remove() {
}
public void setList(ArrayList<T> list) {
this.list = list;
size = list.size();
i = 0;
}
private Iterator() {}
}
}
You should not use for each in Android games.
I think this official video talks about that too.
Probably the best approach would be to use a Decorator design. Create a class which takes a collection in the constructor and implements the Iterable interface by calling the wrapped class and reusing the iterator returned.
Two additional approaches for avoiding the allocation of iterators.
First is to use a callback idiom:
public interface Handler<T> {
void handle(T element);
}
public interface Handleable<T> {
void handleAll(Handler<T> handler);
}
public class HandleableList<T> extends ArrayList<T> implements Handleable<T> {
public void handleAll(Handler<T> handler) {
for (int i = 0; i < size(); ++i) {
handler.handle(get(i));
}
}
}
This approach still requires an instance of a Handler to receive the callback, but this can definitely reduce allocations when, for example, you are trying to visit the elements of several lists.
Second approach is to use a cursor idiom:
public interface Cursor<T> {
void reset();
boolean next();
T current();
}
public class CursoredList<T> extends ArrayList<T> implements Cursor<T> {
private int _index = -1;
public void reset() {
_index = -1;
}
public boolean next() {
return ++_index >= size();
}
public T current() {
return get(_index);
}
}
Sure, this is the same as implementing Iterable and Iterator on your subtype of ArrayList, but this clearly shows the cursor location as state on the collection itself.

Is there a fixed sized queue which removes excessive elements?

I need a queue with a fixed size. When I add an element and the queue is full, it should automatically remove the oldest element.
Is there an existing implementation for this in Java?
Actually the LinkedHashMap does exactly what you want. You need to override the removeEldestEntry method.
Example for a queue with max 10 elements:
queue = new LinkedHashMap<Integer, String>()
{
#Override
protected boolean removeEldestEntry(Map.Entry<Integer, String> eldest)
{
return this.size() > 10;
}
};
If the "removeEldestEntry" returns true, the eldest entry is removed from the map.
Yes, Two
From my own duplicate question with this correct answer, I learned of two:
EvictingQueue in Google Guava
CircularFifoQueue in Apache Commons
I made productive use of the Guava EvictingQueue, worked well.
To instantiate an EvictingQueue call the static factory method create and specify your maximum size.
EvictingQueue< Person > people = com.google.common.collect.EvictingQueue.create( 100 ) ; // Set maximum size to 100.
I just implemented a fixed size queue this way:
public class LimitedSizeQueue<K> extends ArrayList<K> {
private int maxSize;
public LimitedSizeQueue(int size){
this.maxSize = size;
}
public boolean add(K k){
boolean r = super.add(k);
if (size() > maxSize){
removeRange(0, size() - maxSize);
}
return r;
}
public K getYoungest() {
return get(size() - 1);
}
public K getOldest() {
return get(0);
}
}
There is no existing implementation in the Java Language and Runtime. All Queues extend AbstractQueue, and its doc clearly states that adding an element to a full queue always ends with an exception. It would be best ( and quite simple ) to wrap a Queue into a class of your own for having the functionality you need.
Once again, because all queues are children of AbstractQueue, simply use that as your internal data type and you should have a flexible implementation running in virtually no time :-)
UPDATE:
As outlined below, there are two open implementations available (this answer is quite old, folks!), see this answer for details.
This is what I did with Queue wrapped with LinkedList, It is fixed sized which I give in here is 2;
public static Queue<String> pageQueue;
pageQueue = new LinkedList<String>(){
private static final long serialVersionUID = -6707803882461262867L;
public boolean add(String object) {
boolean result;
if(this.size() < 2)
result = super.add(object);
else
{
super.removeFirst();
result = super.add(object);
}
return result;
}
};
....
TMarket.pageQueue.add("ScreenOne");
....
TMarket.pageQueue.add("ScreenTwo");
.....
public class CircularQueue<E> extends LinkedList<E> {
private final int capacity;
public CircularQueue(int capacity){
this.capacity = capacity;
}
#Override
public boolean add(E e) {
if(size() >= capacity)
removeFirst();
return super.add(e);
}
}
Usage and test result:
public static void main(String[] args) {
CircularQueue<String> queue = new CircularQueue<>(3);
queue.add("a");
queue.add("b");
queue.add("c");
System.out.println(queue.toString()); //[a, b, c]
String first = queue.pollFirst(); //a
System.out.println(queue.toString()); //[b,c]
queue.add("d");
queue.add("e");
queue.add("f");
System.out.println(queue.toString()); //[d, e, f]
}
I think what you're describing is a circular queue. Here is an example and here is a better one
This class does the job using composition instead of inheritance (other answers here) which removes the possibility of certain side-effects (as covered by Josh Bloch in Essential Java). Trimming of the underlying LinkedList occurs on the methods add,addAll and offer.
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
public class LimitedQueue<T> implements Queue<T>, Iterable<T> {
private final int limit;
private final LinkedList<T> list = new LinkedList<T>();
public LimitedQueue(int limit) {
this.limit = limit;
}
private boolean trim() {
boolean changed = list.size() > limit;
while (list.size() > limit) {
list.remove();
}
return changed;
}
#Override
public boolean add(T o) {
boolean changed = list.add(o);
boolean trimmed = trim();
return changed || trimmed;
}
#Override
public int size() {
return list.size();
}
#Override
public boolean isEmpty() {
return list.isEmpty();
}
#Override
public boolean contains(Object o) {
return list.contains(o);
}
#Override
public Iterator<T> iterator() {
return list.iterator();
}
#Override
public Object[] toArray() {
return list.toArray();
}
#Override
public <T> T[] toArray(T[] a) {
return list.toArray(a);
}
#Override
public boolean remove(Object o) {
return list.remove(o);
}
#Override
public boolean containsAll(Collection<?> c) {
return list.containsAll(c);
}
#Override
public boolean addAll(Collection<? extends T> c) {
boolean changed = list.addAll(c);
boolean trimmed = trim();
return changed || trimmed;
}
#Override
public boolean removeAll(Collection<?> c) {
return list.removeAll(c);
}
#Override
public boolean retainAll(Collection<?> c) {
return list.retainAll(c);
}
#Override
public void clear() {
list.clear();
}
#Override
public boolean offer(T e) {
boolean changed = list.offer(e);
boolean trimmed = trim();
return changed || trimmed;
}
#Override
public T remove() {
return list.remove();
}
#Override
public T poll() {
return list.poll();
}
#Override
public T element() {
return list.element();
}
#Override
public T peek() {
return list.peek();
}
}
Sounds like an ordinary List where the add method contains an extra snippet which truncates the list if it gets too long.
If that is too simple, then you probably need to edit your problem description.
Also see this SO question, or ArrayBlockingQueue (be careful about blocking, this might be unwanted in your case).
It is not quite clear what requirements you have that led you to ask this question. If you need a fixed size data structure, you might also want to look at different caching policies. However, since you have a queue, my best guess is that you're looking for some type of router functionality. In that case, I would go with a ring buffer: an array that has a first and last index. Whenever an element is added, you just increment the last element index, and when an element is removed, increment the first element index. In both cases, addition is performed modulo the array size, and make sure to increment the other index when needed, that is, when the queue is full or empty.
Also, if it is a router-type application, you might also want to experiment with an algorithm such as Random Early Dropping (RED), which drops elements from the queue randomly even before it gets filled up. In some cases, RED has been found to have better overall performance than the simple method of allowing the queue to fill up before dropping.
Actually you can write your own impl based on LinkedList, it is quite straight forward, just override the add method and do the staff.
I think the best matching answer is from this other question.
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.
A Simple solution, below is a Queue of "String"
LinkedHashMap<Integer, String> queue;
int queueKeysCounter;
queue.put(queueKeysCounter++, "My String");
queueKeysCounter %= QUEUE_SIZE;
Note that this will not maintain the Order of the items in the Queue, but it will replace the oldest entry.
As it's advised in OOPs that we should prefer Composition over Inheritance
Here my solution keeping that in mind.
package com.choiceview;
import java.util.ArrayDeque;
class Ideone {
public static void main(String[] args) {
LimitedArrayDeque<Integer> q = new LimitedArrayDeque<>(3);
q.add(1);
q.add(2);
q.add(3);
System.out.println(q);
q.add(4);
// First entry ie 1 got pushed out
System.out.println(q);
}
}
class LimitedArrayDeque<T> {
private int maxSize;
private ArrayDeque<T> queue;
private LimitedArrayDeque() {
}
public LimitedArrayDeque(int maxSize) {
this.maxSize = maxSize;
queue = new ArrayDeque<T>(maxSize);
}
public void add(T t) {
if (queue.size() == maxSize) {
queue.removeFirst();
}
queue.add(t);
}
public boolean remove(T t) {
return queue.remove(t);
}
public boolean contains(T t) {
return queue.contains(t);
}
#Override
public String toString() {
return queue.toString();
}
}
Ok, I'll throw out my version too. :-) This is build to be very performant - for when that matters. It's not based on LinkedList - and is thread safe (should be at least). FIFO
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
}
}

Categories