Cannot implement Queue - does not override abstract method offer(java.lang.Object) - java

I am trying to implement the Java 1.6 Queue interface, but I am getting the error:
MyBoundedQueue.java:27: MyBoundedQueue is not abstract and does not override abstract method offer(java.lang.Object) in java.util.Queue
What I really don't understand is that there is no offer(Object) method in the Queue class. The Java 1.6 API for Queue says there is a method boolean offer(E e), where E is a parameterized type, and indeed, I have implemented that, as shown below.
Any help?
import java.util.ArrayDeque;
import java.util.Iterator;
import java.util.Queue;
public class MyBoundedQueue<ItemType> implements Queue
{
private int _maxSize;
private ArrayDeque<ItemType> _window;
public MyBoundedQueue(int maxSize)
{
_maxSize = maxSize;
_window = new ArrayDeque<ItemType>(_maxSize);
}
public boolean add(ItemType item)
{
if (_window.size() >= _maxSize)
{
_window.removeFirst();
}
_window.addLast(item);
}
public ItemType element()
{
return _window.element();
}
public boolean offer(ItemType item)
{
add(item);
return true;
}
public ItemType peek()
{
return _window.peek();
}
public ItemType poll()
{
return _window.poll();
}
public ItemType remove()
{
return _window.remove();
}
public void clear()
{
_window.clear();
}
public int size()
{
return _window.size();
}
public Iterator<ItemType> iterator()
{
return _window.iterator();
}
}

You need to change it to:
public class MyBoundedQueue implements Queue<ItemType>
It's telling you offer(Object) because without the Generic typing that's what it would be. You also don't need to specify a generic type for your class ... you're not using generic types anywhere.
If you wanted your class to use generics you'd want to do:
public class MyBoundedQueue<T> implements Queue<T> {
...
And everywhere you currently have ItemType you'd use T instead.

Please stick to coding conventions and use a single, upper-case letter for type parameters!
You'll need to implement Queue<T> (or Queue<ItemType> if you insist)

Is ItemType a fixed class, or is it supposed to be a parameter?
If it's fixed, it should be class MyBoundedDeque implements Queue<ItemType>, not the other way around.
Otherwise, it should be class MyBoundedQueue<ItemType> implements Queue<ItemType>.

Change to
MyBoundedQueue implements Queue<ItemType>
Your code is equivalent to
MyBoundedQueue implements Queue<Object>

Related

Avoid using multiple if-else statements

Item is an abstract class with subclasses Potion, Weapon. Shield.
The useItem() method is an abstract method defined in each of Item's subclasses
get_item return object of class Item
The getItem method returns an object of class subclass of Item
case "use":
if (hero.get_item() instanceof Potion) {
hero.<Potion>getItem(Potion.class).useItem();
} else if (hero.get_item() instanceof Weapon) {
hero.<Weapon>getItem(Weapon.class).useItem();
} else if (hero.get_item() instanceof Shield) {
hero.<Shield>getItem(Shield.class).useItem();
}
break;
is there a way I can condense this code into something like...
Class itemclass = hero.getItem().getClass();
hero.<itemclass>getItem(itemclass.class).useItem();
The code above does not compile but I am looking for something like it. I am trying to avoid if else statements because there are many more items.
Edit:
The reason i did not initially use hero.get_item().useItem() was because
i was trying to do
Weapon sword = hero.get_item();
so i could access methods such as sword.getDamage()
However, I would get the error error: incompatible types: Item cannot be converted to a Weapon
so that is why I created (help from #marsouf) hero.<Weapon>getItem(Weapon.class)
Today i created the method abstract public void useItem();
and since it is a method of the Item class I am able to use hero.getItem().useItem()
It would make more sense to haven an Interface for Item with the method useItem().
Then have an implementation for Potion, Shield etc.
This way you avoid having to cast and make it more complex than it is.
useItem() does not belong in the abstract class if its not giving any functionality, and less needed now Interfaces can have default methods.
My idea is to use the magic of generics without not cast
public class Character<T extends Item> {
private T item;
public Character (T item){
this.item = item;
}
public T getItem(){
return item;
}
}
When you create a hero:
Character hero = new Character<Weapon>(new Weapon("sword"));
after this you can use it like:
hero.getItem().useItem(); // abstract method from Item class
hero.getItem().getPower(); //where power is a Weapon method
Character class you can extend like:
public class Hero<T> extend Character<T>{
//add there your custom methods or override Character methods
}
Difficult to answer without seeing the contracts being involved (hero.get_item(), hero.getItem()).
But have you tried:
Class<?> itemClass = hero.get_item().getClass();
hero.getItem(itemClass).useIt();
?
Assuming you are set on using generics the way you're using them... here's how.
First, I've created some extremely simple classes to mimic your structure from this and your other question: a class which uses instances of a particular abstract class.
public class ACOne extends AbstractClass
{
#Override
public void use(){System.out.println("Used item ACOne!");}
}
public class ACTwo extends AbstractClass
{
#Override
public void use(){System.out.println("Used item ACTwo!");}
}
public abstract class AbstractClass
{
public abstract void use();
}
public class UserClass
{
private AbstractClass item;
public UserClass (AbstractClass item)
{
this.item = item;
}
public Class<? extends AbstractClass> getItemClass()
{
return item.getClass();
}
public <T extends AbstractClass> T getItem (Class <? extends T> targetType)
{
return targetType.cast(this.item);
}
public void setItem (AbstractClass item)
{
this.item = item;
}
}
public class CastingSubclasses
{
public void testCastingSubclasses()
{
UserClass user = new UserClass(new ACOne());
user.setItem(new ACTwo());
user.getItem(user.getItemClass()).use();
}
}
This program, when run, prints out "Used item ACTwo!"
The crux here is in the getItemClass method on the UserClass (your Character class).
Also, it's common to call these methods which get the Class object 'getClazz', since there is a default method 'getClass' that you don't want to override.
Here it made sense to just keep the spelling.

Method declaration in superclass

I wan't to make a method declaration in a superclass called 'dataItem' so that all subclasses that implement that method must have a return type that is of that implementing class. Is that possible?
For example if I have class 'Experiment' which implements 'dataItem' and I have method newItem() . Which for 'Experiment' should only be able to return 'Experiment' datatype and not any other implementation of 'dataItem'.
You can't force a class method to return the type it is a member of. You have to actually specify it.
public class DataItem {
public DataItem getItem() {return null;}
}
public class Experiment extends DataItem {
#Override
public Experiment getItem() {return null;}
}
This works because Experiment is a sub class of DataItem and can therefore be used anywhere a DataItem could be used.
I suppose you're looking for this:
public interface dataitem<T>
{
public T newItem();
};
public class Element implements dataitem<Element>
{
#Override
public Element newItem()
{
return new Element();
}
}

Force a generic type to be an interface?

It looks like this is impossible to do, but does anyone have a clever way around this problem?
public class SomeClassIterableWrapper<S, T extends SomeClass & S> implements Iterable<S>
Where S is supposed to be an interface of some unknown type and SomeClass is a 2D array with a row index, similar in functionality to a bidirectional JDBC resultset. Subclasses of SomeClass have custom getters and setters for each column. I want to be able to iterate through this structure like I would a List. I want to implement a common interface between my SomeClass and Bean to have access to the getters and setters. As such S needs to be that interface. However the declaration I provided does not work. Is there a way to work around this?
edit to show my desired implementation:
public class SomeClassIterableWrapper<S, T extends SomeClass & S> implements Iterable<S>{
T object;
public SomeClassWrapper(T object){
this.object = object;
}
#Override
public Iterator<S> iterator() {
object.setIndex(-1);
return new SomeClassIterator<S>();
}
private class SomeClassIterator<S> implements Iterator<S> {
#Override
public boolean hasNext() {
return object.index() < object.rowSize() - 1;
}
#Override
public S next() {
object.next();
//safe because only interface methods allowed, can't further manipulate index
return object;
}
#Override
public void remove() {
object.deleteRow();
}
}
Can't you parameterize SomeClass with S? Then you could have
public class SomeClassIterableWrapper<S, T extends SomeClass<S>>
implements Iterable<S>{
I think the S in extends SomeClass & S
public class SomeClassIterableWrapper
has to be a definite class because in this context,
S has to be a class that is extending something.
Is there a way you can narrow down what the
potential classes that are used in place of S are?
You could use multiple ampersands if you have multiple
classes that T should extend
I confess that I don't fully comprehend the problem but this is what I suggest:
Create an interface of S. It contains one method ad it returns the S object.
public interface SWrapper<S> {
S getS();
}
Then create an implementation:
public class SImpl implements SWrapper<SImpl> {
#Override
public SImpl getS() {
return this;
}
}
You can now create:
public class SomeClass<T extends SomeClass & SWrapper<T>> {
private final T object;
public SomeClass(T object) {
this.object = object;
}
}
You will have to modify your usage a bit but perhaps it works.

Using Generics with Abstract Data Types in Java

For a CS class I need to solve an assigned problem using three data structures: Queue, PriorityQueue, and Stack. I wanted to write a single solution to the problem using an abstract data structure. I would implement the ADT with a wrapper class of each required data type. This is what I have so far:
An interface called Method:
public interface Method<E> {
public abstract void add(E data);
public abstract E remove();
public abstract E peek();
public abstract Iterator<E> Iterator();
}
And three wrapper classes that implement the interface. I called them QueueMethod, StackMethod, and PriorityQueueMethod. I'm having some trouble implementing the interface though. This is a start for the implementation that gives the error "Class is not abstract and does not override abstract method add(java.lang.Object)." As far as I can tell the signature of the two add methods are identical.
Here's the beginning QueueMethod wrapper class:
public class PriorityQueueMethod<T> implements Method {
PriorityQueue<T> queue;
public PriorityQueueMethod() {
queue = new PriorityQueue<T>();
}
public void add(T data) {
queue.offer(data);
}
}
Add generic to the Method class you are implementing, like this:
public class PriorityQueueMethod<T> implements Method<T>
Use the generic signature in your implements declaration:
public class PriorityQueueMethod<T> implements Method<T>
Here's a sample implementation for an ArrayList based solution:
public class ArrayListMethod<T> implements Method<T>{
private final List<T> inner;
public ArrayListMethod(){
inner = new ArrayList<T>();
}
public ArrayListMethod(final Collection<T> data){
inner = new ArrayList<T>(data);
}
#Override
public void add(final T data){
inner.add(data);
}
#Override
public T remove(){
return inner.remove(0);
}
#Override
public T peek(){
return inner.get(0);
}
#Override
public Iterator<T> Iterator(){
return inner.iterator();
}
}

Good way to have a Collection Listener?

Is there a better way to have a listener on a java collection than wrap it in a class implementing the observer pattern ?
You should check out Glazed Lists
It contains observable List classes, which fire events whenever elements are added, removed, replaced, etc
You can using the ForwardingSet, ForwardingList, etc., from Guava to decorate a particular instance with the desired behavior.
Here's my own implementation that just uses plain JDK APIs:
// create an abstract class that implements this interface with blank implementations
// that way, annonymous subclasses can observe only the events they care about
public interface CollectionObserver<E> {
public void beforeAdd(E o);
public void afterAdd(E o);
// other events to be observed ...
}
// this method would go in a utility class
public static <E> Collection<E> observedCollection(
final Collection<E> collection, final CollectionObserver<E> observer) {
return new Collection<E>() {
public boolean add(final E o) {
observer.beforeAdd(o);
boolean result = collection.add(o);
observer.afterAdd(o);
return result;
}
// ... generate rest of delegate methods in Eclipse
};
}
Apache Events.
"Commons-Events provides additional classes for firing and handling events. It focusses on the Java Collections Framework, providing decorators to other collections that fire events."
Well, if you don't actually need a java.util.Collection or List instance, you could use a DefaultListModel. I'm not aware of any "real" Collection implementations with builtin listener/observer support.
there are many ways to achieve this - often i use this approach
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class ObservableArrayList<E> extends ArrayList<E> {
private #interface MethodId {
private static final int REMOVE = 2;
private static final int ADD = 1;
}
public interface ListObserver<E> {
void onElementAdded(E element);
void onElementRemoved(E element);
}
public ObservableArrayList(int capacity) {
super(capacity);
ensureObserver();
}
public ObservableArrayList() {
ensureObserver();
}
public ObservableArrayList(Collection<? extends E> collection) {
super(collection);
ensureObserver();
}
private List<WeakReference<ListObserver<E>>> _listObserverWeakRefList;
public void addObserver(ListObserver<E> observer) {
_listObserverWeakRefList.add(new WeakReference<ListObserver<E>> (observer));
}
private void ensureObserver() {
if (_listObserverWeakRefList == null) {
_listObserverWeakRefList = new ArrayList<>();
}
}
#Override
public boolean add(E object) {
super.add(object);
callObservable(MethodId.ADD, object);
return true;
}
#Override
public boolean remove(Object object) {
boolean removed = super.remove(object);
if (removed) callObservable(MethodId.REMOVE, object);
return removed;
}
private void callObservable(#MethodId int methodId, Object element) {
for (WeakReference<ListObserver<E>> observerRef : _listObserverWeakRefList) {
ListObserver<E> observer = observerRef.get();
if (observer != null) {
switch (methodId) {
case MethodId.ADD:
observer.onElementAdded((E) element);
break;
case MethodId.REMOVE:
observer.onElementRemoved((E) element);
break;
}
}
}
}
}

Categories