Error calling add in a Hashset

Asked

Viewed 79 times

1

Every time I try to create a objeto.add(); and put the attribute in it, it continue to give me an error. See my code:

public class Agencia {
    private String nome;
    private String endr;
    Set<Conta> listaContas = new HashSet<Conta>();

    private int nrAgencia;

    public Agencia(int pNrAgencia, String pNome, String pEndr){
        this.setNome(pNome);
        this.setEndr(pEndr);
        this.setNrAgencia(pNrAgencia);

        //AQUI ESTA
        //O Netbens me informa que ha um erro, e não consigo resolver
        listaContas.add(pNrAgencia);

    }

 //Outra Classe
 public class Conta {
      Conta(int pnrConta,  double pSaldo, Agencia agencia,Pessoa ptitular){
        System.out.println("Nome:");
        ptitular.setNome(scan.nextLine());

        System.out.println("Endereço:");
        ptitular.setEndr(scan.nextLine());

        this.setNrConta(pnrConta);
        this.setSaldo(pSaldo);

        //Agencia
         System.out.println("Informe o numero da agencia");
        agencia.setNrAgencia(scan.nextInt());
    }

    public Conta() {

    }
  • 3

    listaContas is a Set<Conta>, then you can only add instances of Conta in it. You tried to add pNrAgencia, which is a int (and not a Conta), therefore the mistake.

  • in case I will instantiate the account class, inside the hashset ?

  • You create a Conta and then adds her to the HashSet

  • it has as to make a small simple example, because I did it and gave error, it may be that I am not understanding.

1 answer

1


public class Agencia {
    private String nome;
    private String endr;
    Set<Conta> listaContas = new HashSet<Conta>();

    private int nrAgencia;

    public Agencia(int pNrAgencia, String pNome, String pEndr){
       Conta conta = new Conta();
        listaContas.add(conta); 
    //o Set não aceita duplicidade e não garante ordenação 
    // e também esta tipado para receber o tipo conta então ele deve receber conta

    }
  • I love you man, thank you very much

  • @Vitor Just one detail, new Conta() creates an "empty" account (without the fields filled, so no number, balance, agency and holder). It makes sense to create an empty account and add it in listaContas when you create an agency? When you create an agency, it can start without any account, and new HashSet already initializes listaContas, then you wouldn’t even have to create and add the empty account. Even the constructor without parameters is something to be evaluated, understand better by reading this link: https://answall.com/q/73530/112052

  • @Victor Another detail is that it is recommended that objects that are added in one HashSet implement equals and hashcode. Understand better by reading here, here, here and here

Browser other questions tagged

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