简体   繁体   中英

How to print different parts of a List in Java

I want to know how to print a List in Java where in each position there is a String and an int.

List pasajeros = new ArrayList();

I insert the data like this:

public void insert(List a) {
        System.out.print("Name: ");
        name= sc.nextLine();
        System.out.print("Number: ");
        number= sc.nextInt();
        ClassName aero = new ClassName(name, number);
        a.add(aero);
    }
}

And it seems to work like this, but in the syso gives me an error.

So you have a list of ClassName .

To print them, you can simply use a for loop:

List<ClassName> pasajeros = new ArrayList<>();
// + insert elements
for (ClassName cn : pasajeros) {
    System.out.println("Name: " + cn.getName() + ", number: " + cn.getNumber());
}

You are printing an object without overriding the toString method..

list.Aerolinea@154617c means you are printing the objects hashcode.. so your problem is not at inserting, is at printing out the objects that the list is holding, in this case your Aerolinea class must override properly the toString method.

something like:

class Aerolinea {
    private String nombre;
    private String apellido;
    @Override
    public String toString() {
    return "Aerolinea [nombre=" + nombre + ", apellido=" + apellido + "]";
    }
}

Try like put method toString in your class...

public class Aerolinea {
String nombre;
.......
.......
public String toString() {
    return "nombre" = nombre;
    }
}

Ok I fixed it finally, it was silly... I forgot to write < ClassName> in the method. Here is the final code

public void vertodo(List<Aerolinea> a) {
    for (Aerolinea cn : a) {
        System.out.println("Name: " + cn.name+ " ID: " + cn.id);
    }
}

since I had created it like List pasajeros = new ArrayList(); , then I changed it to List<Aerolinea> pasajeros = new ArrayList(); .

Although I can't write the final <> empty after ArrayList as some have recommended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM