列出打印奇怪的值而不是字符串

时间:2019-07-01 17:46:07

标签: java list

我制作了一个方法,该方法创建一个列表,并使用FOR循环用“ Dog”对象填充该列表,最后打印出列表中的内容。但是,当我运行它时,而不是打印字符串,而是打印出类似“ list.Dog@eed1f14”

public class Dog {
    private  String breed;
    private  String name;
    Scanner s = new Scanner(System.in);



  public void makeList(){
        System.out.println("What's ths size of the list?");
        int sizeOfList = s.nextInt();
        List<Dog> dog = new ArrayList<>();
        for (int i = 0; i < sizeOfList; i++) {
            Dog doggy = new Dog(breed, name);
            dog.add(doggy);
            System.out.println("What's the breed of the dog :");
            doggy.breed = s.next();

            System.out.println("What's the name of the dog:");
            doggy.name = s.next();

        }
        dog.forEach(System.out::println);

    }





public class Liste {


    public static void main(String[] args) {

        Dog p = new Dog();
        p.makeList();

    }

}

我希望它返回对象的名称和品种(字符串),而是给了我“ liste.Dog@eed1f14”

1 个答案:

答案 0 :(得分:1)

这是toString method on Object的输出。要获得Dog的更具体的输出,请在toString中覆盖Dog

// Inside the `Dog` class
@Override
public String toString() {
    // Create and return relevant string
}

(注意:@Override注释是可选的,请按照您团队的指导原则说明是否包含此注释。)