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

时间:2015-04-10 16:56:28

标签: java arraylist

我试图接受某人的名字和姓氏,然后将这两个人Strings放在一起ArrayList

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

我有两个课程如下:

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

也许这就是记忆位置?

感谢任何帮助,谢谢。

2 个答案:

答案 0 :(得分:1)

获取你必须要做的名字

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);

答案 1 :(得分:0)

您还可以在Names类中覆盖toString函数,如:

public String toString(){
    return lastName + "  " + firstName;
}

这是将对象值打印为String

的最佳选项
相关问题