Can you remove an object from an Array by its object condition and not by index?

C.Roma :

I've been learning about Java Arrays lately and I'm practicing doing some kind of inventory or pouch where you store, remove and exchange objects.

But I would like to know if there's a way to, for example, remove an object for being that object and not because is in a determinated index in the list...

I have this class with a constructor, that assigns 2 properties: 'Nombre' (name of the object) and adicion (an int, since this could be used in a game we can say this is the number of hp you recover by using a potion)

public class Objetos {
    String nombre;
    int adicion;
    public void objetos(String nomb, int sumar){
        adicion = sumar;
        nombre = nomb;
    }

  public void setNombre (String nomb){
        nombre = nomb;
    }

    public String getNombre(){
        return nombre;
    }  


  public void setAdicion (int sumar){
        adicion = sumar;
    }

    public int getAdicion(){
        return adicion;
    }
}

Then, I have this array of objects:

static Objetos[] objetos_inv = new Objetos[15];
objetos_inv[0] = new Objetos();
objetos_inv[0].nombre = "Potion";
objetos_inv[0].adicion = 20;
System.out.println(objetos_inv[0]);

I added an object, and now of course I can remove, change or print it by his index position (0), but what If I don't know (is happening 100%) the index where a object is going to be placed? I can remove it for being a "potion"?

I'm just learning, probably have a lot of misconceptions, sorry If I said or assume something dumb. Thanks for your attention.

NickAth :

Sort answer: No

In order to remove an element from an array (no matter what type of array) you should know the index of the element you want to remove/edit.

Workarounds for your case

1) In case you have the reference of the object you want to delete

i) Use an implementation of the List class (f.e Arraylist) to store your objects

So when you have the reference of the object you can remove it by using

objetosList.remove(objectToBeDeleted);

ii) Use commons lang's ArrayUtils in your array

ArrayUtils.removeElement(objetos_inv, objectToBeDeleted);

2) In case you do not have the reference of the object you should make a search in your array, by values to get the index of the object you need and then use that index for any further actions.

private Objetos findObjetoByNombre(Objetos[] objetos, String nombre){
   for(Objetos objeto: objetos){
      if(objeto.getNombre().equals(nombre){
         return objeto;
      }
   }
   return null;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=147092&siteId=1