Java operations with collections

I need an advice. I created three classes of Om (Human), Parinte (Father) and Copil (Child). I created the constructors of this class. In the main class, I created one instance for each class. Now I saved my objects in an ArrayList. After that, I will create some methods for processing my objects, for example, sorting them by name A by Z. My question is how to print these objects in a clear String format after I call the sorting methods, because I get every time things like @ ... when I'm just trying to print the value stored in my collection?

My code: Om Class (Human):

public class Om {
String nume;
String prenume;
String cnp;

Om(String nume,String prenume,String cnp){
this.nume=nume;
this.prenume=prenume;
this.cnp=cnp;
}
}

Class My Parinte (Father):

public class Parinte extends Om{
String domiciliu;
Parinte(String nume, String prenume, String cnp, String domiciliu){
    super(nume,prenume,cnp);
    this.domiciliu=domiciliu;
}
}

Class My Copil (Child):

public class Copil extends Parinte {
int varsta;
Copil(String nume, String prenume, String cnp, String domiciliu, int varsta){
    super(nume,prenume,cnp,domiciliu);
    this.varsta=varsta;
}
}

And finally, my main class:

import java.util.ArrayList;
import java.util.Arrays;
public class main {

public static void main(String[] args) {
    Om om1=new Om("Dubolari", "Dragos", "2006004034120");
    Parinte p1=new Parinte("Enache","Andrei","2006004034120","Al. Cel Bun 13");
    Copil c1 = new Copil("Enache","Valeriu","2006004034120","Al. Cel Bun 13",15);
    ArrayList<Om> colectie = new ArrayList<Om>();
    colectie.add(om1);
    colectie.add(p1);
    colectie.add(c1);

}
}
+4
source share
4

toString() . :

public class Copil extends Parinte {
    int varsta;
    Copil(String nume, String prenume, String cnp, String domiciliu, int varsta){
        super(nume,prenume,cnp,domiciliu);
        this.varsta=varsta;
    }

    @Override
    public String toString() {
        return "Copil. Nume" + nume + " Varsta: " + varsta;  //Whatever you want to do here
    }

}

:

for(Om o: colectie){
    System.out.println(o);  //printing calls the toString()
}
+2

, java toString() . , , , (, @)

+1

FastCode, print . . , , , / .

, fastcode , logger.debug, logger.trace, System.out.println, .. . , , , , . . .

System.out.println("args " + args) ;
System.out.println("c1 " + c1) ;
System.out.println("colectie " + colectie) ;
System.out.println("om1 " + om1) ;
System.out.println("p1 " + p1) ;

enter image description here

+1

@number - - .

toString,

toString() Java?

0

Source: https://habr.com/ru/post/1533414/


All Articles