Remove() method does not remove Arraylist object

Asked

Viewed 1,495 times

1

I’m having a doubt to remove an object from a list on a job. I have a car class:

public class Automovel {
     String marca;
     String modelo;
     String preco;



    Automovel(String marca, String modelo, String preco) {
       this.marca = marca;
        this.modelo = modelo;
        this.preco = preco;
    }
// ja esta como geter e seters

I also have a dealership class that implements this class:

package metodista.ads.carro;

import java.util.ArrayList;

/**
 *
 * @author Luiz Ricardo
 */
public class Concessionaria {

    public Concessionaria() {
    }

    ArrayList<Automovel> carros = new ArrayList<>();

    //O método adicionaVeiculo deverá adicionar um veículo ao estoque (atributo listaAutomoveis).
    public void adicionaVeiculo(Automovel automovel){
         carros.add(automovel);
    }
    // O método vendaVeiculo remove um veículo do estoque.
    public void vendaVeiculo(Automovel automovel){
        carros.remove(automovel);
    }

    //O método consultaEstoqueVeiculo devolve os veículos em estoque.
    public String consultaEstoqueVeiculo(){
        return carros.size()+"";
    }


}
//

my main class, has a screen for input user data, my doubt is in the method to remove an Automovel object, I have a button that when being clicked would need to take an auto object from stock, but it does not work:

private void btVenderActionPerformed(java.awt.event.ActionEvent evt) {     
 // construtor concessionaria        
Concessionaria con = new Concessionaria(); 

        String marca = tfMarca.getText();
        String modelo = tfModelo.getText();
        String preco = tfPreco.getText();
        Automovel auto2 = new Automovel(marca, modelo, preco);
        con.vendaVeiculo(auto2);

my main class, has a screen for user data entry, my doubt is in the way of saleDownload to remove an Automovel object.

  • First you need to define a shape and identify each car (as an id for example), without this it is impossible to do what you want.

  • Another thing, your code has a logic error: if you want to remove an existing car, why create a new dealership and a new car when removing? This doesn’t make any sense to what you want to do, so it’s important to provide a [mcve] because the error is not only in that code

  • I can define a way to start the counter indicating q and spoiler the maximum amount of cars in stock, then add and remove, passed p the index of the list ?

1 answer

1

It doesn’t work because the Automovel that the method tries to remove does not exist in Arraylist.

The method remove() uses the standard method implementation equals(), of the object to be removed, to check if it exists in Arraylist.
The standard implementation only checks if it is the same instance.

If it works that way:

ArrayList<Automovel> carros = new ArrayList<>();

Automovel auto1 = new Automovel("marca1", "modelo1", preco);
carros.add(auto1);
Automovel auto2 = new Automovel("marca2", "modelo1", preco);
carros.add(auto2);

carros.remove(auto1);

As the method remove() depends on the method equals() in order to be able to identify when two objects are equal (representing the same entity), it must be overwritten according to equality requirements.

You need to determine which class fields Automovel identify a Automovel, which make it unique and use them in implementing the equals method().

For example, if you consider that two cars are the same if they are of the same make and model, a possible implementation for the equals() method is:

@Override
public boolean equals(Object o) {
    // verifica se é o mesmo objecto
    if (this == o)
        return true;
    // verifica se é null
    if (o == null)
        return false;
    // verifica tipo e cast
    if (getClass() != o.getClass())
        return false;

    Automovel automovel = (Automovel) o;
    // Comparação atributo a atributo
    // Note que cada um dos atributos têm também de implementar correctamente o método equals()
    return  Objects.equals(marca, automovel.marca) &&
            Objects.equals(modelo, automovel.modelo);
}
  • I don’t think that alone would solve the problem. If you notice, it creates a new dealership each time it runs the boot System, IE, will not remove anything because dealership is created always with an empty list.

  • Could then create a vector, stating that it would be a total stock of cars and go adding and removing in the positions?

  • @Article Yes this is also a problem. However, the main issue and perhaps the most useful for AP and others is the superscript of the method equals().

  • @ramaral yes but because it seems to be a swing application and to be a beginner user, it is important to emphasize this too, because in no way will it overwrite the equals method without fixing the problem I mentioned, will continue giving the same error.

  • @Articuno you had already given this information in your comment on the question. This problem is specific to the PA, while the lack of the superscript is more common. It is more likely that this question/answer is sought for the second reason. For these reasons I preferred only to focus on the superscript.

  • Ricardo, this depends on what you want to do. "Normal" is that type of objects have identity, determined by one or more class fields.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.