• 集合ArrayList---回顾toString方法


    没有toString方法:打印的是集合元素的内存地址

    Student.java

    package com.yikuan.test;
    
    public class Student {
        private String name;
        private int age;
        /*构造方法*/
        public Student() {
            super();
        }
        public Student(String name, int age) {
            super();
            this.name = name;
            this.age = age;
        }
        /*toSting方法*/
    //    @Override
    //    public String toString() {
    //        return "Student [name=" + name + ", age=" + age + "]";
    //    }
        /*get、set方法*/
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        
        public void setAge(int age) {
            this.age = age;
        }
    }

    Test.java

    package com.yikuan.test;
    
    import java.util.ArrayList;
    
    public class Test1 {
        public static void main(String[] args) {
            ArrayList<Student> list = new ArrayList<Student>();
            list.add(new Student("aa",12));
            list.add(new Student("ww",14));
            list.add(new Student("qq",15));
            list.add(new Student("ee",51));
            for (int i = 0; i < list.size(); i++) {
                System.out.println(list.get(i));
            }
        }
    }

    结果:

    com.yikuan.test.Student@2a139a55
    com.yikuan.test.Student@15db9742
    com.yikuan.test.Student@6d06d69c
    com.yikuan.test.Student@7852e922

    加上toString:打印集合中的元素值

    结果:

    Student [name=aa, age=12]
    Student [name=ww, age=14]
    Student [name=qq, age=15]
    Student [name=ee, age=51]
  • 相关阅读:
    现代操作系统-读者/写者问题
    现代操作系统-进程互斥
    关于网页强制被跳转到wpkg.org的解决
    Leetcode Count Prime
    Leetcode Add Two Numbers
    Leetcode Two Sum
    can't find -lsocket的解决办法
    删除Windows右键不用的选项
    Linux下的另一个词典GoldenDict
    spark执行例子eclipse maven打包jar
  • 原文地址:https://www.cnblogs.com/yikuan-919/p/9539246.html
Copyright © 2020-2023  润新知