Adding an element to a Java immutable queue - java

I hope that someone can help me with my little problem.
I defined my EmptyQueue and my NotEmptyQueue in this way, following my interface Immutable queue. The main problem it's that the method enQueue, that should add an element to myQueue is not working. Pls help me:
Interface:
public interface ImmutableQueue<E> extends Iterable<E> {
boolean isEmpty();
int size();
ImmutableQueue<E> enQueue(E e);
ImmutableQueue<E> deQueue();
E getTop();
}
EmptyQueue:
import java.util.Iterator;
import java.util.NoSuchElementException;
public class EmptyQueue<E> implements ImmutableQueue <E>, Iterable <E> {
#Override
public boolean isEmpty() {
return true;
}
#Override
public int size() {
return 0;
}
#Override
public ImmutableQueue<E> enQueue(E e) {
NotEmptyQueue<E> q= new NotEmptyQueue <>(e,this);
return q;
}
#Override
public ImmutableQueue<E> deQueue() {
throw new NoSuchElementException();
}
#Override
public E getTop() {
throw new NoSuchElementException();
}
#Override
public Iterator<E> iterator() {
return new Iterator<E>(){
#Override
public boolean hasNext() {
return false;
}
#Override
public E next() {
throw new NoSuchElementException();
}
};
}
}
NotEmptyQueue:
import java.util.Iterator;
public class NotEmptyQueue<E> implements ImmutableQueue<E>, Iterable <E>{
public E e;
public ImmutableQueue<E> tail;
public NotEmptyQueue(E e, ImmutableQueue<E> tail){
this.e = e;
this.tail = tail;
}
#Override
public boolean isEmpty() {
return false;
}
#Override
public int size() {
return tail.size() + 1;
}
#Override
public ImmutableQueue<E> enQueue(E e) {
return new NotEmptyQueue<>(e,this);
}
#Override
public ImmutableQueue<E> deQueue() {
return tail;
}
#Override
public E getTop(){
return e;
}
public static void main (String [] args){
NotEmptyQueue<Integer> myQueue= new NotEmptyQueue<>(new Integer(1),null);
myQueue.enQueue(9);
myQueue.enQueue(7);
System.out.println(myQueue.size());
System.out.println(myQueue.getTop());
for(Integer i : myQueue){
System.out.println(i);
}
}
#Override
public Iterator<E> iterator() {
return new Iterator<E>(){
ImmutableQueue<E> queue;
#Override
public boolean hasNext() {
return (!tail.isEmpty());
}
#Override
public E next() {
E res = queue.getTop();
queue = queue.deQueue();
return res;
}
Iterator<E> setQueue(ImmutableQueue<E> queue){
this.queue = queue;
return this;
}
}.setQueue(this);
}
}

myQueue.enQueue(9);
should be
myQueue = myQueue.enQueue(9);
That's the usual way to deal with a persistent queue like you have.

Related

How is this possible? (Junit exception testing of linked list implementation

I am writing a LinkedList implementation which includes a previous function that returns the position prior to the one passed as an input argument. It should check whether the inputted position is the first one and throw an exception in that case:
#Override
public Position<T> previous (Position<T> p) throws PositionException {
if (this.first(p)) {
throw new PositionException();
}
return this.convert(p).prev;
}
However, the following test is failing because it isn't throwing the expected exception from trying to use the previous function on the first position in the array:
#Test (expected=PositionException.class)
public void gettingPreviousAtFront() {
Position<String> one = list.insertFront("One");
Position<String> two = list.insertFront("Two");
assertTrue(list.first(two));
Position<String> beforeTwo = list.previous(two);
}
There was 1 failure: 1)
gettingPreviousAtFront(hw6.test.LinkedListTest)
java.lang.AssertionError: Expected exception:
exceptions.PositionException at
org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:32)
It is even passing the assertion on line 301 of the test that "two" is first. So how is it possible that the exception is not being thrown by the previous function?
Here is the full linkedlist code:
package hw6;
import exceptions.EmptyException;
import exceptions.PositionException;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class LinkedList<T> implements List<T> {
private static final class Node<T> implements Position<T> {
// The usual doubly-linked list stuff.
Node<T> next; // reference to the Node after this
Node<T> prev; // reference to the Node before this
T data;
// List that created this node, to validate positions.
List<T> owner;
#Override
public T get() {
return this.data;
}
#Override
public void put(T t) {
this.data = t;
}
}
/** This iterator can be used to create either a forward
iterator, or a backwards one.
*/
private final class ListIterator implements Iterator<T> {
Node<T> current;
boolean forward;
ListIterator(boolean f) {
this.forward = f;
if (this.forward) {
this.current = LinkedList.this.sentinelHead.next;
} else {
this.current = LinkedList.this.sentinelTail.prev;
}
}
#Override
public T next() throws NoSuchElementException {
if (!this.hasNext()) {
throw new NoSuchElementException();
}
T t = this.current.get();
if (this.forward) {
this.current = this.current.next;
} else {
this.current = this.current.prev;
}
return t;
}
#Override
public boolean hasNext() {
if (this.forward) {
return this.current != LinkedList.this.sentinelTail;
}
else {
return this.current != LinkedList.this.sentinelHead;
}
}
}
/* ** LinkedList instance variables are declared here! ** */
private Node<T> sentinelHead;
private Node<T> sentinelTail;
private int length; // how many nodes in the list
/**
* Create an empty list.
*/
public LinkedList() {
this.sentinelHead = new Node<>();
this.sentinelTail = new Node<>();
this.sentinelHead.owner = this;
this.sentinelTail.owner = this;
this.sentinelTail.prev = this.sentinelHead;
this.sentinelHead.next = this.sentinelTail;
this.length = 0;
}
// Convert a position back into a node. Guards against null positions,
// positions from other data structures, and positions that belong to
// other LinkedList objects. That about covers it?
private Node<T> convert(Position<T> p) throws PositionException {
try {
Node<T> n = (Node<T>) p;
if (n.owner != this) {
throw new PositionException();
}
return n;
} catch (NullPointerException | ClassCastException e) {
throw new PositionException();
}
}
#Override
public boolean empty() {
return this.length == 0;
}
#Override
public int length() {
return this.length;
}
#Override
public boolean first(Position<T> p) throws PositionException {
Node<T> n = this.convert(p);
return this.sentinelHead.next == n;
}
#Override
public boolean last(Position<T> p) throws PositionException {
Node<T> n = this.convert(p);
return this.sentinelTail.prev == n;
}
#Override
public Position<T> front() throws EmptyException {
if (this.length == 0) {
throw new EmptyException();
}
return this.sentinelHead.next;
}
#Override
public Position<T> back() throws EmptyException {
if (this.empty()) {
throw new EmptyException();
}
return this.sentinelTail.prev;
}
#Override
public Position<T> next(Position<T> p) throws PositionException {
if (this.last(p)) {
throw new PositionException();
}
return this.convert(p).next;
}
#Override
public Position<T> previous(Position<T> p) throws PositionException {
if (this.first(p)) {
throw new PositionException();
}
return this.convert(p).prev;
}
#Override
public Position<T> insertFront(T t) {
return this.insertAfter(this.sentinelHead, t);
}
#Override
public Position<T> insertBack(T t) {
return this.insertBefore(this.sentinelTail, t);
}
#Override
public void removeFront() throws EmptyException {
this.remove(this.front());
}
#Override
public void removeBack() throws EmptyException {
this.remove(this.back());
}
#Override
public void remove(Position<T> p) throws PositionException {
Node<T> n = this.convert(p);
n.owner = null;
n.prev.next = n.next;
n.next.prev = n.prev;
this.length--;
}
#Override
public Position<T> insertBefore(Position<T> p, T t)
throws PositionException {
Node<T> current = this.convert(p);
Node<T> n = new Node<T>();
n.owner = this;
n.data = t;
n.prev = current.prev;
current.prev.next = n;
n.next = current;
current.prev = n;
this.length++;
return n;
}
#Override
public Position<T> insertAfter(Position<T> p, T t)
throws PositionException {
Node<T> current = this.convert(p);
Node<T> n = new Node<T>();
n.owner = this;
n.data = t;
n.next = current.next;
current.next.prev = n;
n.prev = current;
current.next = n;
this.length++;
return n;
}
#Override
public Iterator<T> forward() {
return new ListIterator(true);
}
#Override
public Iterator<T> backward() {
return new ListIterator(false);
}
#Override
public Iterator<T> iterator() {
return this.forward();
}
#Override
public String toString() {
StringBuilder s = new StringBuilder();
s.append("[");
for (Node<T> n = this.sentinelHead.next; n != this.sentinelTail; n = n.next) {
s.append(n.data);
if (n.next != this.sentinelTail) {
s.append(", ");
}
}
s.append("]");
return s.toString();
}
}

Java: How to reverse over an Iterable

I have to reverse a Linked List. Just look at the Method reverse, maybe you could help me because I am desperate ;). Maybe it's doable with the methods below...
Thank you Everyone.
Heres the Code:
import java.util.Iterator;
public class LL<E> implements Iterable<E> {
E head;
LL<E> tail;
String a="[";
public LL(E head, LL<E> tail) {
super();
this.head = head;
this.tail = tail;
}
public LL() {
this(null, null);
}
boolean isEmpty() {
return head == null && tail == null;
}
#Override
public Iterator<E> iterator() {
return new MyIterator(this);
}
private class MyIterator implements Iterator<E> {
LL<E> current;
public MyIterator(LL<E> current) {
super();
this.current = current;
}
#Override
public boolean hasNext() {
return !current.isEmpty();
}
#Override
public E next() {
E result = current.head;
current = current.tail;
return result;
}
E get(int i) throws IndexOutOfBoundsException{//maybe...
E result = current.head;
for(int q=0; q<i;q++){
current=current.tail;
}
return result;
}
boolean contains(E e){//das gleiche nur mit tail
boolean yo=false;
while(hasNext()){
E result= current.head;// oder tail
if(result.equals(e))return yo=true;//unnötig ;)
}
return yo;
}
E last(){//oder nochmal
E result=get(1);
if(hasNext()) {result= next();};
return result;
}
}
public LL<E> limit(int i){
if(i>0&& !isEmpty()){
return new LL<E>(head,tail.limit(i-1));
}
return new LL<E>();
}
public LL<E> drop(int i){
//löschen wie bei limit
if(i>0){
return tail.drop(i-1);
}
return new LL<E>(head,tail);
}
public LL<E> sublist(int from, int to){
//was rauslöschen und limit
LL<E> ersteElemente= this.limit(to);
//erste delete
return ersteElemente.drop(from);
}
public LL<E> reverse(){
//2 schleifen
for(int q=6;q>0;q--){
return this.sublist(q-1, q);
}
}
#Override
public String toString(){
String result="[";
LL<E> n;//for Schleife
//while (tail!=null){
this.forEach((x)-> a+=x+";");
a+="]";
//}
return a;
}
public static void main(String[] args) {
LL<String> xs = new LL<>("Freunde", new LL<>("Römer", new LL<>("Landsleute",
new LL<>("leiht", new LL<>("mir", new LL<>("euer", new LL<>("Ohr", new LL<>())))))));
xs.forEach((x) -> System.out.println(x.toUpperCase()));
for (String x:xs){
System.out.println(x.toUpperCase());
}
System.out.println((xs.toString()));
xs.toString();
System.out.println("END");
}
}
You need to return a value in reverse method
public LL<E> reverse() {
LL<E> result = null;
// 2 schleifen
for (int q = 6; q > 0; q--) {
result = this.sublist(q - 1, q);
}
return result;
}

How do I make my ImmutableList sortable in its ObservableList wrapper?

I have my own implementation of ObservableList called ObservableImmutableList. It wraps a Guava ImmutableList with the ObservableList interface so I can fully utilize ImmutableList easily with JavaFX. There is nothing mutable about it except it allows another ImmutableList to be swapped in as the backing list using the set() method (and notify all listeners/bindings of the change).
However, one problem I ran into is the ObservableImmutableList cannot be sorted. I cannot extend or implement SortedList, so how do I implement it into this class?
I tried to create a method asSorted() which returns the ObservableImmutableList wrapped in a SortedList. But it also would not work. Is there some kind of simple abstract layer I can use to keep the list Immutable but allow the values to be resorted in the abstracted layer?
public final class ObservableImmutableList<T> implements ObservableList<T> {
private volatile ImmutableList<T> backingList;
private final LazyProperty<SortedList<T>> sortedList = LazyProperty.forSupplier(() -> new SortedList<>(this));
private final CopyOnWriteArrayList<ListChangeListener<? super T>> listeners = new CopyOnWriteArrayList<>();
private final CopyOnWriteArrayList<InvalidationListener> invalidationListeners = new CopyOnWriteArrayList<>();
private final ObjectProperty<ObservableList<T>> property;
private ObservableImmutableList(ImmutableList<T> immutableList) {
this.backingList = immutableList;
this.property = new SimpleObjectProperty<ObservableList<T>>(this);
}
public static <T> ObservableImmutableList<T> of(ImmutableList<T> immutableList) {
return new ObservableImmutableList<T>(immutableList);
}
public SortedList<T> asSorted() {
return sortedList.get();
}
public void set(ImmutableList<T> immutableList) {
this.property.setValue(this);
final ImmutableList<T> oldList = this.backingList;
final ImmutableList<T> newList = immutableList;
listeners.forEach(l -> l.onChanged(new Change<T>(this) {
private int changeNum = 0;
#Override
public boolean next() {
changeNum++;
return changeNum <= 2 ? true : false;
}
#Override
public boolean wasUpdated() {
return true;
}
#Override
public void reset() {
// TODO Auto-generated method stub
}
#Override
public int getFrom() {
return 0;
}
#Override
public int getTo() {
return changeNum == 1 ? oldList.size() - 1 : newList.size() - 1;
}
#Override
public List<T> getRemoved() {
return changeNum == 1 ? oldList : ImmutableList.of();
}
#Override
public List<T> getAddedSubList() {
return changeNum == 1 ? ImmutableList.of() : newList;
}
#Override
protected int[] getPermutation() {
int[] permutations = new int[changeNum == 1 ? oldList.size() : newList.size()];
for (int i = 0; i < permutations.length; i++) {
permutations[i] = i;
}
return permutations;
}
}));
this.backingList = immutableList;
invalidationListeners.forEach(l -> l.invalidated(this));
}
public ImmutableList<T> get() {
return backingList;
}
public ObjectProperty<ObservableList<T>> asProperty() {
return property;
}
#Override
public int size() {
return backingList.size();
}
#Override
public boolean isEmpty() {
return backingList.isEmpty();
}
#Override
public boolean contains(Object o) {
return backingList.contains(o);
}
#Override
public Iterator<T> iterator() {
return backingList.iterator();
}
#Override
public Object[] toArray() {
return backingList.toArray();
}
#Override
public <B> B[] toArray(B[] a) {
return backingList.toArray(a);
}
#Override #Deprecated
public boolean add(T e) {
return backingList.add(e);
}
#Override #Deprecated
public boolean remove(Object o) {
return backingList.remove(o);
}
#Override
public boolean containsAll(Collection<?> c) {
return backingList.containsAll(c);
}
#Override #Deprecated
public boolean addAll(Collection<? extends T> c) {
return backingList.addAll(c);
}
#Override #Deprecated
public boolean addAll(int index, Collection<? extends T> c) {
return backingList.addAll(index, c);
}
#Override #Deprecated
public boolean removeAll(Collection<?> c) {
return backingList.removeAll(c);
}
#Override #Deprecated
public boolean retainAll(Collection<?> c) {
return backingList.retainAll(c);
}
#Override #Deprecated
public void clear() {
backingList.clear();
}
#Override
public T get(int index) {
return backingList.get(index);
}
#Override #Deprecated
public T set(int index, T element) {
return backingList.set(index, element);
}
#Override #Deprecated
public void add(int index, T element) {
backingList.add(index, element);
}
#Override #Deprecated
public T remove(int index) {
return backingList.remove(index);
}
#Override
public int indexOf(Object o) {
return backingList.indexOf(o);
}
#Override
public int lastIndexOf(Object o) {
return backingList.lastIndexOf(o);
}
#Override
public ListIterator<T> listIterator() {
return backingList.listIterator();
}
#Override
public ListIterator<T> listIterator(int index) {
return backingList.listIterator(index);
}
#Override
public ImmutableList<T> subList(int fromIndex, int toIndex) {
return backingList.subList(fromIndex, toIndex);
}
#Override
public void addListener(InvalidationListener listener) {
invalidationListeners.add(listener);
}
#Override
public void removeListener(InvalidationListener listener) {
invalidationListeners.remove(listener);
}
#Override
public void addListener(ListChangeListener<? super T> listener) {
listeners.add(listener);
}
#Override
public void removeListener(ListChangeListener<? super T> listener) {
listeners.remove(listener);
}
#Override #Deprecated
public boolean addAll(T... elements) {
return backingList.addAll(ImmutableList.copyOf(elements));
}
#Override #Deprecated
public boolean setAll(T... elements) {
return false;
}
#Override #Deprecated
public boolean setAll(Collection<? extends T> col) {
return false;
}
#Override #Deprecated
public boolean removeAll(T... elements) {
return backingList.removeAll(ImmutableList.copyOf(elements));
}
#Override #Deprecated
public boolean retainAll(T... elements) {
return false;
}
#Override #Deprecated
public void remove(int from, int to) {
}
#Override
public String toString() {
return backingList.toString();
}
}
The part you asked about: a SortedList is just a wrapper around its backing list, it does not change it in any way. So you can wrap any list - mutable or not - into a SortedList and use that in the TableView. In the example of your previous question:
ObservableList<NumericCombo> immutable =
FXCollections.unmodifiableObservableList(values);
// new ImmutableObservableList<>(values);
TableView<NumericCombo> tableView = new TableView<>();
SortedList sorted = new SortedList(immutable);
tableView.setItems(sorted);
sorted.comparatorProperty().bind(tableView.comparatorProperty());
The part you did not ask about (how to get the notifications right).
don't implement ObservableList from scratch, instead go from ObservableListBase
when swapping out the backing list, call the support methods provided by super to notify the listeners
A simple example:
public class ImmutableObservableList<E> extends ObservableListBase<E> {
private List<E> backing;
public ImmutableObservableList(List<E> backingList) {
this.backing = backingList;
}
public void setBackingList(List<E> backingList) {
beginChange();
if (this.backing != null) {
nextRemove(0, this.backing);
}
this.backing = backingList;
if (backingList != null) {
nextAdd(0, backingList.size());
}
endChange();
}
#Override
public E get(int index) {
if (backing == null) throw new IndexOutOfBoundsException();
return backing.get(index);
}
#Override
public int size() {
return backing != null ? backing.size() : 0;
}
}

Java sorted and iterable Defaultlistmodel

I'm trying to extend the DefaultListModel so it will be sort-able and iterable. I found some code here http://www.javalobby.org/java/forums/t94074.html. I'm now trying to parameterize this code, but the addAll,containsAll,removeAll,retainAll, and toArray methods all give a name clash error. I kind of understand why this is, but I'm unsure how to fix it. Is there a better way to do this? Code below
package main;
import javax.swing.DefaultListModel;
import javax.swing.*;
import java.util.*;
public class DefaultListModelSort<E extends Object> extends DefaultListModel<E>
implements List<E> {
private Delegate m_delegate = new Delegate();
public DefaultListModelSort() {
super();
}
public DefaultListModelSort(Collection<E> c) {
this();
addAll(c);
}
public boolean add(E o) {
return m_delegate.add(o);
}
public boolean removeE(E o) {
return m_delegate.remove(o);
}
public boolean addAll(int index, Collection<E> c) {
return m_delegate.addAll(index, c);
}
public boolean addAll(Collection<E> c) {
return m_delegate.addAll(c);
}
public boolean containsAll(Collection<E> c) {
return m_delegate.containsAll(c);
}
public boolean removeAll(Collection<E> c) {
return m_delegate.removeAll(c);
}
public boolean retainAll(Collection<E> c) {
return m_delegate.retainAll(c);
}
public Iterator<E> iterator() {
return m_delegate.iterator();
}
public List<E> subList(int fromIndex, int toIndex) {
return m_delegate.subList(fromIndex, toIndex);
}
public ListIterator<E> listIterator() {
return m_delegate.listIterator();
}
public ListIterator<E> listIterator(int index) {
return m_delegate.listIterator(index);
}
public E[] toArray(E a[]) {
return m_delegate.toArray(a);
}
/**
* This class extends AbstractList so we get all the functionality of
* iterators and such for free.
*/
private class Delegate extends AbstractList<E> {
public Delegate() {
super();
}
public E get(int index) {
return DefaultListModelSort.super.get(index);
}
public int size() {
return DefaultListModelSort.super.size();
}
public E set(int index, E element) {
return DefaultListModelSort.super.set(index, element);
}
public void add(int index, E element) {
DefaultListModelSort.super.add(index, element);
}
public E remove(int index) {
return DefaultListModelSort.super.remove(index);
}
}
}
I'm trying to extend the DefaultListModel so it will be sort-able and
iterable.
use JTable with one Column, JTableHeader can be removed
for more info about RowSorter to read Oracle tutorial How to use Tables - Sorting and Filtering

Does Not Take Parameters in Java [duplicate]

This question already has answers here:
Incompatible Types Error in Java
(2 answers)
Closed 9 years ago.
I'm receiving the error "type Stack does not take parameters public class ArrayStack implements Stack" from this code:
public class ArrayStack<E> implements Stack<E> {
private E[] data;
private int size;
public ArrayStack() {
data = (E[])(new Object[1]);
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public Object pop() {
if (isEmpty()) {
throw new EmptyStructureException();
}
size--;
return data[size];
}
public Object peek() {
if (isEmpty()) {
throw new EmptyStructureException();
}
return data[size - 1];
}
protected boolean isFull() {
return size == data.length;
}
public void push(Object target) {
if (isFull()) {
stretch();
}
data[size] = target;
size++;
}
protected void stretch() {
E[] newData = (E[])(new Object[data.length * 2]);
for (int i = 0; i < data.length; i++) {
newData[i] = data[i];
}
data = newData;
}
}
"type Stack does not take parameters public class ArrayStack implements Stack"
The stack class is as follows.
public interface Stack<E> {
public boolean isEmpty();
public E peek();
public E pop();
public void push(E target);
}
Your peek() method should like this
public E peek() throws EmptyStructureException {
if (isEmpty()) {
throw new EmptyStructureException();
}
return (E)data[size - 1];
}
Your push() method should like this
public void push(E target) {
if (isFull()) {
stretch();
}
data[size] = target;
size++;
}
Your pop() method should like this
public E pop() throws EmptyStructureException {
if (isEmpty()) {
throw new EmptyStructureException();
}
size--;
return (E)data[size];
}
Now your interface look like below
public interface Stack<E> {
public boolean isEmpty();
public E peek() throws EmptyStructureException;
public E pop() throws EmptyStructureException;
public void push(E target);
}

Categories

Resources