I have an object in an ArrayList and I want to print the object on my screen but I can't do it with those getters. How can I do this?

public void start() {
            ArrayList rij = new ArrayList();
            rij.add(new Persoon("Foo","Bar",18));
            rij.add(new Persoon("Jane","Doe",52));
            rij.add(new Persoon("John","Doe",23));

            for(int i = 0; i < 3; i++){
                System.out.println((Persoon)rij.get(i).getNaam() + " " + rij.get(i).getVoornaam() + " " + rij.get(i).getLeeftijd());
            }
        }



    private String naam = "";
        private String voornaam = "";
        private int leeftijd = 0;

        public Persoon(String naam, String voornaam, int leeftijd){
            this.naam = naam;
            this.voornaam = voornaam;
            this.leeftijd = leeftijd;
        }

        public String getNaam(){
             return naam;
        }

        public String getVoornaam(){
            return voornaam;
        }

        public int getLeeftijd(){
            return leeftijd;
        }
有帮助吗?

解决方案

The problem is your cast to Persoon is being applied to rij.get(i).getNaam(), not to rij.get(i).

What you want is:

((Persoon)rij.get(i)).getNaam() etc

Or more simply:

for(int i = 0; i < 3; i++){
    Persoon p = rij.get(i);
    System.out.println(p.getNaam() + " " + p.getVoornaam() + " " + p.getLeeftijd());
}

The parentheses matter. You have know exactly what you're casting and when.

其他提示

Don't use a raw ArrayList. Use a generic one:

This will ensure type-safety, and allow you to avoid casts completely.

List<Persoon> personen = new ArrayList<Persoon>();
//...

for (int i = 0; i < personen.size(); i++) {
    System.out.println(personen.get(i).getNaam() + " " + personen.get(i).getVoornaam() + " " + personen.get(i).getLeeftijd());
}

Using the foreach loop will also lead to safer and more readable code:

List<Persoon> personen = new ArrayList<Persoon>();
//...

for (Persoon persoon : personen) {
    System.out.println(persoon.getNaam() + " " + persoon.getVoornaam() + " " + persoon.getLeeftijd());
}

If you want to print Person object, Try this and Override toString() method in your Person class

System.out.println((Persoon)rij.get(i));

i would recommend in the case you are storing obect like "People" in your case.Its always better to use "iterator"

 ArrayList rij = new ArrayList();
        rij.add(new Persoon("Foo","Bar",18));
        rij.add(new Persoon("Jane","Doe",52));
        rij.add(new Persoon("John","Doe",23));
        Iterator item=rij.iterator();
        while (item.hasNext()){
            Persoon person=(Persoon)item.next();
            System.out.println(person.getNaam() + " " + person.getVoornaam() + " " + person.getLeeftijd());
        }

java.util.iterator;

hope it ll work.If not tell me i ll forward the complete code.. :D

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top