Entity cannot be converted to ArrayList<Entity> - java

I want to read out the first element of an ArrayList. The problem is when i construct a return method i get an error saying 'Entity cannot be converted to ArrayList'. The return function needs to be a public ArrayList, because i'm using a foreach to return the values. Can someone tell me what i'm doing wrong and what i can do to improve this?
Entity manager (public ArrayList) doesn't work.
public class EntityManager {
private Handler handler;
private Player player;
private ArrayList<Entity> entities;
private int counter = 0;
private Comparator<Entity> renderOrder = new Comparator<Entity>(){
#Override
public int compare(Entity a, Entity b) {
if(a.getY() + a.getHeight() < b.getY() + b.getHeight())
return -1;
return 1;
}
};
public EntityManager(Handler handler, Player player){
this.handler = handler;
this.player = player;
entities = new ArrayList<Entity>();
addEntity(player);
}
public void tick(){
Iterator<Entity> it = entities.iterator();
while(it.hasNext()){
Entity e = it.next();
e.tick();
if(!e.isActief()){
it.remove();
counter();
if(counter > entities.size() + 1){
player.eindspel = true;
}
}
}
entities.sort(renderOrder);
}
public void render(Graphics g){
for(Entity e : entities){
e.render(g);
}
player.postRender(g);
}
public ArrayList<Entity> getEntities() {
return entities.get(0);
}
public void counter(){
counter++;
}
public void addEntity(Entity e){
entities.add(e);
}
public void setHandler(Handler handler) {
this.handler = handler;
}
public void setPlayer(Player player) {
this.player = player;
}
public void setEntities(ArrayList<Entity> entities) {
this.entities = entities;
}
public Handler getHandler() {
return handler;
}
public Player getPlayer() {
return player;
}
}
The foreach i'm am using to read out the values from getEntities
for(Entity e : handler.getWereld().getEntityManager().getEntities()){
if(e.equals(this)){
continue;
}
if(e.getCollisionBounds(0, 0).intersects(ar)){
if(opslag.delete()){
e.delete(2);
}
}
}
The outcome i want is when e intersects i want to delete the entity that i get with 'return entities.get(0)', so the first entity of my entities arraylist. only that method won't work and when i use 'return entities' all of my entites get deleted, instead of only the first one.

If you would generalize your external interface to use List instead of ArrayList (see here why that's a good idea), you could just use Collections.singletonList to construct a list containing the first entity.
However, it seems pretty unintuitive to me to have a method called getEntities that just returns one entity. I still don't really get when you want to get all entities, and when just one. Maybe you can edit your question to explain your use case a little more

you are calling delete(int ) method on an Entity
e.delete(2);
and the method is applicable to collection I think it it were your problem comes from.

Related

Create new Instance of Child Class

I have an array list of Enemies and each enemy kind extends enemy. Now I don't wan't every same enemy kind to share all their stats, but I base my enemy selection of another array list. So I think the way to go would be to get the object of the array list containing all the options and then changing them to new Instances of the same class. My question is, how would I do that? Or do you guys have a better approach?
For easy of understanding here's what I mean abstracted
class shop{
ArrayList<Enemy> allEnemies;
}
class generator{
ArrayList<Enemies> selectedToGenerate = based on some of allEnemies
for(Enemy x : selectedToGenerate){ // i know this wouldn't work
x = newInstanceOf(x.getNonenemyThereforeChildclassClass());
}
}
hope this explains what I mean. Appreciate your time!
You can add a Builder to your Enemy.
abstract class Enemy {
private int strength;
public Builder<Enemy> getBuilder();
public static class Builder<T extends Enemy> {
int str;
public Builder<T> copyValues(T enemy) {
str = enemey.strength;
return this;
}
public Builder<T> strength(int s) {
str = s;
return this;
}
protected void fillValues(T toFill) {
toFill.strength = str;
}
protected abstract T createInstance();
public T build() {
T result = createInstance();
fillValues(result);
return result;
}
}
}
This Builder can create instances of your Enemy and fill it with values. For subclasses, you can extend the Builder by allowing it to fill more values.
class EnemyA extends EnemyA {
private int speed;
public Builder<EnemyA> getBuilder() {
return new Builder();
}
class EnemyABuilder extends Builder<EnemyA> {
int speed;
public EnemyABuilder copyValues(EnemyA enemy) {
super.copyValues(enemy);
speed = enemy.speed;
}
public EnemyABuilder speed(int s) {
speed = s;
return this;
}
protected void fillValues(EnemyA toFill) {
super.fillValues(toFill);
toFill.speed = speed;
}
protected EnemyA createInstance() {
return new EnemyA();
}
}
}
Now, you can create copies of the enemies by using their builders:
for(Enemy x : selectedToGenerate){ // i know this wouldn't work
Builder<? extends Enemy> builder = x.getBuilder();
builer.copyValues(x);
Enemy copy = builder.build();
}
As an additional bonus, you can use the builder to quickly create different versions of the same enemy.
EnemyA.Builder base = new Builder().strength(10);
EnemyA withSpeed1 = base.speed(1).build();
EnemyA withSpeed2 = base.speed(2).build();
EnemyA withSpeed3 = base.speed(3).build();

Is it possible to avoid duplicate code when implementing methods for two similar class?

I have two classes: Fish and Plant. They do not inherit from any classes.
But both of them have one method called isAlive() which have the same implementation details. Now I have a list of fish and another list of dog and I need to remove dead fish and dead dog. I want my method to have same name but it is not possible without adding additional field to method signature. Is it possible I do not need to write additional chunk of code which does the same as the last chunk of code?
Below is the code. For class Model, Fish and Plant are two data members and they are ArrayList of Fish and Plant objects.
Is there any way I can write only one method called count and I do not need to add additional field to my method signature or modify my return type?
public class Fish{
public boolean isAlive(){
if(this.size > 0){
return true;
}
return false;
}
}
public class Plant{
public boolean isAlive(){
if(this.size > 0){
return true;
}
return false;
}
}
public class Model{
private int countDeadFish() {
int totalCount = 0;
for(Fish aFish : this.fish) {
if(aFish.isAlive() == false) {
totalCount += 1;
}
}
return totalCount;
}
private int countDeadPlants() {
int totalCount = 0;
for(Plant plant : this.plants) {
if(plant.isAlive() == false) {
totalCount += 1;
}
}
return totalCount;
}
}
If you do not want to use inheritance, then you can use a common method:
public class AliveChecker {
public static boolean isAlive(int size) {
return size > 0;
}
}
public class Plant{
public boolean isAlive(){
return AliveChecker.isAlive(this.size);
}
}
public class Fish{
public boolean isAlive(){
return AliveChecker.isAlive(this.size);
}
}
Since Fishand Plant do not inherit from anything yet you can consider creating a superclass and extend from it:
public class LivingThing {
protected int size = 1;
public boolean isAlive() {
return size > 0;
}
}
public class Plant extends LivingThing {
}
public class Fish extends LivingThing {
}
This example uses inheritance to classify Plantand Fish into the superclass LivingThing. You can set the size for example in the constructor of the Plant or an instance method:
public class Plant extends LivingThing {
public Plant(int size){
this.size = size;
}
}
Your Model could then be:
public class Model{
private int countDeadFish() {
return countDead(this.fish);
}
private int countDeadPlants() {
return countDead(this.plants);
}
private int countDead(ArrayList<LivingThing> things) {
int totalCount = 0;
for(LivingThing thing: things) {
if(!thing.isAlive()) {
totalCount++;
}
}
return totalCount;
}
}
Use interface
public interface LiveObject {
boolean isAlive();
}
public class Fish implements LiveObject {
public boolean isAlive(){
if(this.size > 0){
return true;
}
return false;
}
}
public class Plant implements LiveObject {
public boolean isAlive(){
if(this.size > 0){
return true;
}
return false;
}
}
public class Model{
private int countDead(Collection<LiveObject> objects) {
int totalCount = 0;
for(LiveObject obj : objects) {
if(obj.isAlive() == false) {
totalCount += 1;
}
}
return totalCount;
}
private int countDeadFish() {
return countDead(this.fish);
}
}
Based on the comments it seems you can't modify Fish or Plant. Here's an approach to reduce duplication in countDead<Something> methods which does not require this.
Basically you want to count items in an array which satisfy certain criteria. With Java 8 you can capture this criteria in a predicate using lambdas or method references. You do not need inheritance or implementation of a certain interface for this.
private long countDeadFish() {
return countDeadItems(this.fish, Fish::isAlive);
}
private long countDeadPlants() {
return countDeadItems(this.plants, Plant::isAlive);
}
private <T> long countDeadItems(Collection<T> items, Predicate<? super T> isAlive) {
return items.stream().filter(isAlive.negate()).count();
}
You could create a utility method (in a utility class somewhere):
public final class Liveliness {
private Liveliness() {
}
public static boolean isAlive(final IntSupplier sizer) {
return sizer.getAsInt() > 0;
}
}
Your method then becomes:
public boolean isAlive(){
return Liveliness.isAlive(this::getSize);
}
Alternatively, use an interface Life:
public interface Life {
int getSize();
default boolean isAlive(){
return getSize() > 0;
}
}
This way, adding a getSize method and inheriting from Life will add the method.
Note, avoid the following antipattern:
if(test) {
return true;
} else {
return false;
}
Use return test.

Undo Implementation [duplicate]

I am implementing an undo/redo function which requires me to use memento pattern.
The flow of the partial program : "...the program then store the previous Vector using Memento Pattern, then the newly created object will be added to the Vector. After that, user may choose a show command to show what is inside the Vector, he can also enter undo command to restore, the undo can be repeated until it is restored to the original state..."
From my research, I know there will be an originator, memento and caretaker.
Here's my caretaker program
public class CareTaker {
private Memento m;
private Stack s;
private Vector v;
// Some of the implementation are not shown
public void create() {
// Some of the implementation are not shown
// Assuming Vector is named "v"
// Passing Vector to memento
m = new Memento(v);
s.add(m);
}
public void undo() {
v = s.pop().restore();
}
}
public class Memento {
private Vector _v;
public Memento(Vector v) {
_v = v;
}
public Vector restore() {
return _v;
}
}
Unfortunately , I failed to identify the "Originator" nor I know which one will be.
Is this code fragment ever a correct Memento pattern if there is no Originator?
The memento pattern is used to save the state of an object without knowing it's internal data structures.
I try to explain it with an Iterator example
public class MementoListIterator<E> implements Iterator<E> {
public static class Memento {
private int savedIndex;
private Memento(MementoListIterator<?> mementoListIterator) {
this.savedIndex = mementoListIterator.index;
}
}
private List<E> elements;
private int index = 0;
public MementoListIterator(List<E> elements) {
this.elements = elements;
}
public Memento save() {
return new Memento(this);
}
public void restore(Memento memento) {
this.index = memento.savedIndex;
}
#Override
public boolean hasNext() {
return this.index < elements.size();
}
#Override
public E next() {
return elements.get(index++);
}
#Override
public void remove() {
throw new UnsupportedOperationException("Not implemented yet");
}
}
A client can now save any state of the iterator without knowing how the iterator internally manages it's state.
public class Main {
public static void main(String[] args) {
List<String> list = Arrays.asList("A", "B", "C", "D", "E");
MementoListIterator<String> mementoListIterator = new MementoListIterator<String>(
list);
Memento initialState = mementoListIterator.save();
while (mementoListIterator.hasNext()) {
String string = mementoListIterator.next();
System.out.println(string);
}
// Normally we can not re-use the iterator, but
// fortuanatly we saved the initial state.
// restore the initial state and we can use the Iterator again
mementoListIterator.restore(initialState);
while (mementoListIterator.hasNext()) {
String string = mementoListIterator.next();
System.out.println(string);
}
}
}

For loops and too many if else how to test

I have a code which goes like this
List insert;
List update;
List delete
for(SomeObject someObj : someObjects){
if(isNew){
insert.add()
}
else if(isUpdate){
update.add();
}
if(isDelete){
delete.add()
}
}
//call update insert delete functions
The problem is this code is untestable because the update insert delete are all void methods.
My question is , should I consider iterating over the loop three times and then get the lists to test if the logic to filter each type of results is working? The cost is not that much since I am expecting <100 elements in the list.
You can check
(sum of lists sizes after) == (sum of lists sizes before) + someObjects.size();
The key here is to be able to control the dependencies and access the state that this method acts upon.
Here is an example that illustrates that:
interface SomeDao {
void add(SomeObject object);
void update(SomeObject object);
void delete(SomeObject object);
}
class SomeDaoStub implements SomeDao {
#Override public void add(SomeObject object) {}
#Override public void update(SomeObject object) {}
#Override public void delete(SomeObject object) {}
}
class SomeObject {
private final boolean isNew;
private final boolean isUpdated;
private final boolean isDeleted;
SomeObject(boolean isNew, boolean isUpdated, boolean isDeleted) {
this.isNew = isNew;
this.isUpdated = isUpdated;
this.isDeleted = isDeleted;
}
public boolean isNew() {
return isNew;
}
public boolean isUpdated() {
return isUpdated;
}
public boolean isDeleted() {
return isDeleted;
}
}
public void doSomethingComplicatedWithListsInAForLoop(Iterable<SomeObject> someObjects, SomeDao dao) {
for (SomeObject someObject : someObjects) {
if (someObject.isNew()) {
dao.add(someObject);
} else if (someObject.isUpdated()) {
dao.update(someObject);
} else if (someObject.isDeleted()) {
dao.delete(someObject);
}
}
}
#Test
public void itDeletesObjectsMarkedToBeDeleted() {
final List<SomeObject> actualDeletedObjects = new ArrayList<>();
List<SomeObject> expectedDeletedObjects = Arrays.asList(
new SomeObject(false, false, true),
new SomeObject(false, false, true),
new SomeObject(false, false, true)
);
SomeDao theDao = new SomeDaoStub() {
#Override
public void delete(SomeObject object) {
actualDeletedObjects.add(object);
}
};
doSomethingComplicatedWithListsInAForLoop(expectedDeletedObjects, theDao);
assertEquals(expectedDeletedObjects, actualDeletedObjects);
}
The only reason that I can figure out what doSomethingComplicatedWithListsInAForLoop manipulated is because I can control its dependencies, namely, in this example, SomeDao.
It is likely that you are finding difficulty testing your method because it makes calls to state which you cannot inject.

RxAndroid. Simple caching and filtering data

I read a ton of literature about the Rx and, on the one hand, everything is clear, but on the other hand nothing is clear. I'm trying to do a simple filtration and storage of data from the server with this library, and it is not working as expected. I need to implement a simple channel list management:
1. Cache on disk and in memory
2. When user requested - return filtered channels
3. All Subscribers that was attached to this Observable must be notified if filtered cahnnels list was changed (call onNext() for all Subscribers)
I wrote the following:
ArrayList<Channel> channels = null;
ArrayList<Channel> filteredChannels = null;
Observable<ArrayList<Channel>> filteredObservable = Observable.create()
// here I need to check if cache is valid, if no - download from server
// then filter channels and return filteredChannels in onNext call
// all subscribers that called subscribe before and not called unsubscribe must be notified if filteredChannels changed
// how to implement this?
.subscribeOn(Schedulers.io());
public void setFilter(Filter filter) {
// update filteredChannels with the new filter and notify all Subscribers (call onNext()). How to implement this?
}
public Observable<ArrayList<Channel>> getFilteredChannels() {
return filteredObservable;
}
Do I correctly understood logic of the Rx pattern or not? Thanks in advance.
I would use .map()'s function to filter your list and then return your desired output. This would mean that your Observable would be emitting the filtered results.
Then you could commit the filtered list to your cache in your .subscribe() functions.
I found the solution for this task: I need to use flatMap and map and I tried to use BehaviourSubject to notify all subscribers for variable change, but this solution is not stable at all, because of error MissingBackpressureException, that's why I wrote next ObsevableValue class:
public class ObservableValue<T> {
private static final String TAG = ObservableValue.class.getSimpleName();
private ArrayList<Registration> subscriptions = new ArrayList<>();
private T value;
private int index;
private boolean firstNotify;
private ReentrantLock lock = new ReentrantLock();
public ObservableValue() {
firstNotify = false;
}
public ObservableValue(T defaultValue) {
value = defaultValue;
firstNotify = true;
}
#SuppressWarnings("unchecked")
public void setValue(T value) {
lock.lock();
this.value = value;
for (Registration listener: subscriptions) {
if (!listener.isFinished()) {
listener.getListener().valueChanged(value);
}
}
lock.unlock();
}
public T getValue() {
lock.lock();
T result = value;
lock.unlock();
return result;
}
public Registration subscribe(ValueChangeListener<T> listener) {
lock.lock();
Registration s = new Registration(this, index, listener);
index++;
subscriptions.add(s);
if (firstNotify||value!=null) {
listener.valueChanged(value);
}
lock.unlock();
return s;
}
protected void finish(int index) {
lock.lock();
for (int i=0;i<subscriptions.size();i++) {
Registration s = subscriptions.get(i);
if (s.getIndex()==index) {
subscriptions.remove(i);
break;
}
}
lock.unlock();
}
}
public abstract class ValueChangeListener<T> {
private Looper looper;
public ValueChangeListener() {}
public ValueChangeListener(Looper looper) {
this.looper = looper;
}
public void valueChanged(T data) {
if (looper!=null) {
Handler handler = new Handler(looper, msg -> {
onValueChanged(data);
return true;
});
handler.sendEmptyMessage(0);
} else {
onValueChanged(data);
}
}
public abstract void onValueChanged(T data);
}
public class Registration {
private ObservableValue observableValue;
private int index;
private ValueChangeListener listener;
private volatile boolean finished = false;
protected Registration(ObservableValue observableValue, int index, ValueChangeListener listener) {
this.observableValue = observableValue;
this.index = index;
this.listener = listener;
}
protected ValueChangeListener getListener() {
return listener;
}
protected int getIndex() {
return index;
}
public boolean isFinished() {
return finished;
}
public void finish() {
finished = true;
observableValue.finish(index);
}
}
Now it is working as expected. Like in Rx ObservableValue returns a Registration object that need to be finished() when it is not needed anymore.

Categories