Searching for an object inside an Arraylist

Asked

Viewed 6,310 times

3

I created a class Conta and defined its attributes. Elsewhere in the code, I set values for its attributes and added it to a ArrayList, now I need to select it and print the value of one of its attributes, but I’m not getting it, follow the code:

class Account:

public static class Conta {
    //definindo a classe conta

    int numero;
    String nome_titular;
    double saldo;

    //método para depósito
    void depositar(double valor) {
        this.saldo = this.saldo + valor;
    }

    //método para saque
    boolean sacar(double valor) {
        if (valor > this.saldo) {
            return false;
        } else {
            this.saldo = this.saldo - valor;
            return true;
        }
    }
}

Definition of attribute values:

            c.numero = qtdContas;
            System.out.println("Digite o Nome do titular da conta:");
            sc.nextLine();
            c.nome_titular = sc.nextLine();
            System.out.println("Digite o Saldo da conta:");
            c.saldo = sc.nextDouble();
            System.out.println("Conta criada! Numero da conta = " + c.numero);

            Contas.add(c);

Select and print one of your attributes:

            if (Contas.isEmpty() == true) {
                System.out.println("Não há contas cadastradas!");
            } else {
                System.out.println("Digite o número da conta:");
                int nmrConta = sc.nextInt();
                Conta auxiliar = new Conta();
                auxiliar = Contas.get(nmrConta);
                System.out.println(auxiliar.saldo);
            }
  • Does this code compile? The class is static, and you’re giving new Conta(),

2 answers

7

Good to start:

All Java API classes, user-defined classes, or classes of any other API - extend the java.lang.Object class, implicitly or explicitly. [MALA GUPTA, 2015, p. 51]

With that in mind, when we think about implementing a class (java class design), in the context here would be the: class Conta, we have the aspects

  • Importance of the method equals() searching and removing values from an Arraylist.
  • Importance of override of the method equals().

We should worry about the following tip:

If you are adding instances of a user-defined class as elements to an Arraylist, replace your equals() method or your methods contains() or remove() may not behave as expected. [MALA GUPTA, 2015, p. 281]

To avoid this it is indicated that the method is overwritten equals(), in our case, as follows:

public boolean equals(Object obj) {
    if (obj instanceof Conta) {
       Conta conta = (Conta)obj;
       /** 
        * Considerando apenas o atributo numero para se comparar os objetos.  
        * Alteração do método `equals()` sugerida pelo @Wryel.
        */
        if (conta.numero == this.numero)
           return true;
    }
    return false;
}

NOTE: Modification of the method equals() suggested by @Wryel following the concepts of DDD [Vaughn Vernon, 2013].

For a general approach we have:

Rules for method override equals()

Method equals() defines an elaborate contract (ruleset) as follows (directly from the Java API documentation):

1. It is reflective - For any non-zero reference value x, x.equals (x) must return true. This rule states that an object must be equal to itself, which is reasonable.

2. It is symmetrical - For any non-zero reference values x and y, x.equals(y) must return true if and only if y.equals(x) returns true. This rule states that two objects must be comparable to each other in the same way.

3. It shall be transitive - For any non-zero reference values x, y, and z, if x.equals (y) returns true and y.equals (z) returns true, then x.equals (z) must return true. This rule indicates that when comparing objects, you should not selectively compare values based on the type of an object.

4. It is consistent - For any non-zero xey reference values, the multiple invocations of x.equals (y) consistently return true or consistently return false, provided that no information used in equal comparisons in objects is modified. This rule indicates that the equals() method should rely on the value of instance variables that can be accessed from memory and should not attempt to rely on values such as a system’s IP address, which can be assigned a separate value after reconnecting to a network.

5. - For any nonnull reference value x, x.equals(null) must return false. This rule indicates that a nonnull object can never be equal to null.

It’s good to consider too:

A method improperly overriding the method equals() does not mean compilation failure.[MALA GUPTA, 2015, p. 58]

It is relevant to understand that an Arraylist is an object of the List interface, and that in our question context the method is used get() marked below:

List Interfaces

SOURCE: Figure 4.12 List interface methods, grouped by their functionality [MALA GUPTA, 2015, p. 277]

NOTE: There are considerations about the superscript character of the method hashCode(), but I believe it escapes the scope of the question.


Reference:
[MALA GUPTA, 2015], OCP Java SE 7 Programmer II Certification Guide: PREPARE FOR THE 1ZO-804 EXAM
[Vaughn Vernon, 2013], Domain-Driven Design - DDD: Implementing Domain-Driven Design

  • if you change the implementation of the equals method to just check the account number, the algorithm rule will be correct :o)

  • @wryel, yes it can be, yes. But who ensures that somewhere in the something algorithm is added an object counts 1 [number=333, balance 25.00] different. And you have to remove this same object? And it was found as first occurrence obj1[number=333, balance 27.00] the equals() method will return the obj1 erroneously because it only considered the number attribute.

  • 2

    the contract of equals is precisely to represent equality between two objects. According to the concept of account (in the real world), one account is only the same as the other if the number of the accounts is equal not ? rs

  • True! You are absolutely right. Seeking to model using the concepts of Domain Driven Design - Area Code. Great comment!

4


The Account class is OK if you remove the modifier static. Use static can’t use this, because static classes cannot be instantiated, that is, they cannot have objects created with the new.

I created an executable class with its code with some adaptations to see it running. Note that I kept the essence of the original code. Note: Exceptions if they occur are not being treated.

Follows the code:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class TestConta
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner( System.in );

        List<Conta> contas = new ArrayList<>();

        System.out.print("Digite a quantidade de contas que serão criadas:");
        int qtdContas = sc.nextInt();

            System.out.println("------------------------------");

        for(int i=1; i<=qtdContas; i++)
        {
            Conta c = new Conta();

            //System.out.println("Digite o número da conta:");
            c.numero = i; //sc.nextInt();

            System.out.print("Digite o Nome do titular da conta:");
            c.nome_titular = sc.next();

            System.out.print("Digite o Saldo da conta:");
            c.saldo = sc.nextDouble();


            System.out.println("Conta criada! Numero da conta = " + c.numero);

            contas.add(c);

            System.out.println("------------------------------");
        }


        System.out.println("=========================================================");

        //Verificando as contas criadas

        if (contas.isEmpty() == true) 
        {
            System.out.println("Não há contas cadastradas!");
        } 
        else 
        {
            System.out.print("Digite o número da conta:");
            int nmrConta = sc.nextInt();
            nmrConta--; //pq ao invés de começar o for de zero, começamos de 1, mas guardamos no elemento 0 do array

            Conta auxiliar = contas.get(nmrConta);
            System.out.println("Nome do titular:" + auxiliar.nome_titular);
            System.out.println("Saldo da conta:" +auxiliar.saldo);
        }            
    }

}

Example of output generated if data are entered correctly to cause no exceptions:

Digite a quantidade de contas que serão criadas:3
------------------------------
Digite o Nome do titular da conta:Lucas
Digite o Saldo da conta:100
Conta criada! Numero da conta = 1
------------------------------
Digite o Nome do titular da conta:Alexandre
Digite o Saldo da conta:500
Conta criada! Numero da conta = 2
------------------------------
Digite o Nome do titular da conta:Diogo
Digite o Saldo da conta:1000
Conta criada! Numero da conta = 3
------------------------------
=========================================================
Digite o número da conta:2
Nome do titular:Alexandre
Saldo da conta:500.0    

If this answer has been useful to help solve the problem, accept it as a response and give +1 by clicking the arrow up to give me reputation points of the site. If in doubt, ask in the comments.

  • Thank you, helped a lot, now it’s working perfectly <3 worth even

Browser other questions tagged

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