简体   繁体   English

如何在Java中打印列表的不同部分

[英]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. 我想知道如何在Java中打印一个列表,其中每个位置都有一个字符串和一个整数。

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. 它似乎像这样工作,但是在syso中给了我一个错误。

So you have a list of ClassName . 因此,您有一个ClassName列表。

To print them, you can simply use a for loop: 要打印它们,您可以简单地使用for循环:

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.. 您在打印对象时不会覆盖toString方法。

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. list.Aerolinea@154617c意味着您正在打印对象哈希码..因此,您的问题不在插入,而是在打印出列表所保存的对象,在这种情况下,您的Aerolinea类必须正确覆盖toString方法。

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... 尝试在类中使用put方法toString。

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. 好的,我终于修复了它,这很愚蠢...我忘了在方法中写<ClassName>。 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(); 因为我创建它的方式类似于List pasajeros = new ArrayList(); , then I changed it to List<Aerolinea> pasajeros = new ArrayList(); ,然后将其更改为List<Aerolinea> pasajeros = new ArrayList(); .

Although I can't write the final <> empty after ArrayList as some have recommended. 尽管我不能像某些人建议的那样在ArrayList之后写最后的<>为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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