Java sorted and iterable Defaultlistmodel - java

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

Related

How can I create a queue only given the implemented methods?

I have a class MyList with the following methods :
public class MyList{
ArrayList<Object> list;
MyList(int a, int b)
{
list = new ArrayList<Object>();
for(;a<=b;a++)
list.add(a);
}
public void add(int index, Object o)
{
list.add(index, o);
}
public Object remove(int index) throws isEmptyException
{
if(isEmpty())
throw new isEmptyException();
else
return list.remove(index);
}
public boolean isEmpty()
{
return list.isEmpty();
}
Here's my Class Queue. I have to implement the following methods using only the above methods from MyList.
public class Queue extends MyList{
public void enqueue(Object o)
{
//adds a new Object to the queue
}
public Object dequeue()
{
//removes the next Object from the queue and returns it
}
public boolean empty()
{
//Checks if the queue is empty
}
I don't really know where to start here, since I don't know the size of the queue. Can someone give me a hint how to solve this? Is a recursive method useful here?
Thanks in advance!
Call the add or remove inside the enqueue and dequeue methods of the Queue class, maintain a pointer to first and last.
public class Queue extends MyList {
private int index;
private int firstIndex;
Queue(int a, int b)
{
super(a, b);
}
public void enqueue(Object o)
{
add(o);
index++;
}
public Object deueue() throws Exception {
if(firstIndex == index || isEmpty()) {
firstIndex =0; index =0;
throw new Exception("");
}
else
return list.remove(++firstIndex);
}
public boolean isEmpty()
{
return list.isEmpty();
}
}

Compiler asking for optional methods from Collections to be overridden

I'm creating a class-wide project with my school mates, I'm supposed to create pull requests for some functions, but I'm having some problems just creating the class and overriding the methods in a way that it would just compile (I don't need to write the methods at this moment, that's the project, I just need it to compile). I've found most methods are working (or at least the compiler is not complaining), but I'm confused about a few things:
Compiler complaining about methods that are optional (like set, and addAll)
The method addAll, although it was added, complains that it wasn't overridden, although it was, and when I add the other addAll method for it, then I get an erasure error as well.
I've read a bunch about it, but I couldn't find a proper conclusion on how to solve it. I'm just using Atom to write my code, and the Terminal, no fancy IDE (perhaps I should learn one).
In case it isn't clear, I'm just looking to have the stubs of the methods available, not an all around answer for every single method, since this is the project with the class.
// https://docs.oracle.com/javase/8/docs/api/java/util/List.html
import java.util.*;
import java.lang.reflect.*;
public class SkipList<E> implements List<E>
{
// compiler complaining, then added, although optional
public E set(int index, E element)
{
throw new IndexOutOfBoundsException();
}
// compiler complaining, then added, although optional
public boolean addAll(Collection <? extends E> c)
{
return true;
}
// Group 1
public boolean add(E e)
{
return true;
}
public void add(int index, E e)
{
}
public boolean addAll(Collection c)
{
return true;
}
public int indexOf(Object o)
{
int index = 0;
return index;
}
public int lastIndexOf(Object o)
{
int index = 0;
return index;
}
// Group 2
public boolean contains(Object o)
{
return true;
}
public boolean containsAll(Collection c)
{
return true;
}
public boolean equals(Object o)
{
return true;
}
public List<E> subList(int fromIndex, int toIndex)
{
List<E> sub = new SkipList<>();
return sub;
}
// Group 3
public boolean isEmpty()
{
return true;
}
public int size()
{
int size = 0;
return size;
}
public void clear()
{
}
public E get(int index)
{
throw new IndexOutOfBoundsException();
}
public E getQuantile(double quantile) // e.g. 0 = minimum, 0.5 = median, 1 = max
{
throw new IndexOutOfBoundsException();
}
// Group 4
public Iterator<E> iterator()
{
throw new IndexOutOfBoundsException();
}
public ListIterator<E> listIterator()
{
throw new IndexOutOfBoundsException();
}
public ListIterator<E> listIterator(int index)
{
throw new IndexOutOfBoundsException();
}
// Group 5
public E remove(int index)
{
throw new IndexOutOfBoundsException();
}
public boolean remove(Object o)
{
return true;
}
public boolean removeAll(Collection c)
{
return true;
}
public boolean retainAll(Collection c)
{
return true;
}
// Group 6
public int hashCode()
{
int hashCode = 0;
return hashCode;
}
public Object[] toArray()
{
Object[] arr = new Object[0];
return arr;
}
public <T> T[] toArray(T[] a)
{
return a;
}
}
Turns out that when reading the API, for some reason I glossed over the other parameter for the addAll method, that led me to believe something else was wrong. I changed the method with the correct parameters and it compiled.
public boolean addAll(int index, Collection <? extends E> c)
{
return true;
}

Java Mutable data structures

Why do I keep getting an error when I try to execute this method,
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.ArrayList;
import java.util.HashSet;
public class BIAOperations <T extends Comparable<T>, E> implements Set<T>
{
private HashSet<T> Set;
public BIAOperations(){
Set = new HashSet<T>();
}
#Override
public boolean isEmpty()
{
if(Set.isEmpty())
{
return true;
}
else
return false;
}
#Override
public int size(){
return Set.size();
}
#Override
public int compareTo(Set<T> o) {
return 0;
}
#Override
public List<T> toList() {
List<T> list = new ArrayList<T>();
list.addAll(Set);
return list;
}
#Override
public Set<T> add(T x) {
Set.add(x);
return this;
}
#Override
public Set<T> remove(T x) {
Set.remove(x);
return this;
}
#Override
public boolean contains(T x)
{
if(Set.contains(x))
return true;
}
else
{
return false;
}
The error which I get is at the contains method at the bottom of the code.
the error I keep getting is void methods cannot return a value and on else I keep getting syntax error on else delete this token.
The else block is outside the method. Fix it as follows:
#Override
public boolean contains(T x)
{
if(Set.contains(x))
return true;
else
return false;
}
EDIT: you can also shorten this code as per #Unholysheep's suggestion in the comment.
#Override
public boolean contains(T x)
{
return Set.contains(x);
}
Also, as per #domdom's suggestion in the comment, use a better name for your object. In Java, I would recommend you use names starting with a small letter for your objects. Typically, names starting with a upper case letter are used for Class names. So instead of Set, use set or customSet or something for your object.

Adding an element to a Java immutable queue

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.

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;
}
}

Categories

Resources