如何在Java中打印出List的所有元素? [英] How to print out all the elements of a List in Java?

查看:5977
本文介绍了如何在Java中打印出List的所有元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试打印出 List 的所有元素,但是它正在打印对象的指针而不是价值。

I am trying to print out all the elements of a List, however it is printing the pointer of the Object rather than the value.

这是我的打印代码......

This is my printing code...

for(int i=0;i<list.size();i++){
    System.out.println(list.get(i));
} 

有人可以帮我解释为什么它不打印元素的价值。

Could anyone please help me why it isn't printing the value of the elements.

推荐答案

以下是关于打印列表组件的一些示例:

Here is some example about getting print out the list component:

public class ListExample {

    public static void main(String[] args) {
        List<Model> models = new ArrayList<>();

        // TODO: First create your model and add to models ArrayList, to prevent NullPointerException for trying this example

        // Print the name from the list....
        for(Model model : models) {
            System.out.println(model.getName());
        }

        // Or like this...
        for(int i = 0; i < models.size(); i++) {
            System.out.println(models.get(i).getName());
        }
    }
}

class Model {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

这篇关于如何在Java中打印出List的所有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆