java - 无法输出使用两个对象的ArrayList

标签 java arraylist

我正在尝试获取某人的名字和姓氏,然后获取这两个 Strings并将它们放入一个 ArrayList一起。

我可以接受两个Strings ,但问题是我无法输出它们。

我有两个类(class),如下:

import java.util.ArrayList;
import java.util.Scanner;


public class TakeInName {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        ArrayList<Names> studentNames = new ArrayList<Names>();
        Names newName = new Names();

        newName.firstName = scan.nextLine();
        newName.lastName = scan.nextLine();

        studentNames.add(newName);

        Names item = studentNames.get(0);

        System.out.print(item);

    }
}

第二个:

public class Names {
    String lastName;
    String firstName;
}

我什至不确定我是否让第二类正确地能够用它做任何事情?也许这就是我的问题?

当我运行此代码时,得到的输出是: Names@5c647e05

也许这就是内存位置?

感谢任何帮助,谢谢。

最佳答案

要获取您必须执行的操作

System.out.print(item.firstName+" "+item.lastName);

因为您正在获取 Names 对象。您获得的字符串(Names@5c647e05) 是预期的。它是对象的字符串表示形式,其中 Name 是类,@ 连接字符串的字符,以及 5c647e05 一些哈希码

回复评论。

代码是

Names newName1=new Names();
newName1.firstName = scan.nextLine();
newName1.lastName = scan.nextLine();
studentNames.add(newName1);

Names newName2=new Names();                //create new object for new name
newName2.firstName = scan.nextLine();
newName2.lastName = scan.nextLine();
studentNames.add(newName2);
Names item = studentNames.get(0);
System.out.print(item.firstName + " " + item.lastName);
Names item1 = studentNames.get(1);
System.out.print(item1.firstName + " " + item1.lastName);

关于java - 无法输出使用两个对象的ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29566833/

相关文章:

java - 为什么 Java List 遍历比文件 readline 慢?

Java 数组和数组列表

java - 为什么 SocketChannel 调用 read(byteBuffer) 会抛出 java.net.SocketException : recvfrom failed: ECONNRESET (Connection reset by peer)

java - 将 db4o 与 Netbeans 结合使用

java - java列表只显示一次项目,但计算它们的出现次数?

Java:在构造函数中自动递增 id 并将项目添加到 arraylist

java - 从适配器向模型数组对象添加值

java - 资源使用过多 : memcached Linux Centos 7

java - Java 中有没有办法找到传递给函数的变量的名称?

java - Swingworker超时