简体   繁体   English

如何从某些类型的数组列表中返回值?

[英]How do I return values from certain type of array list?

Is this program doable with just getters or print statements, or should I consider doing it differently? 该程序仅适用于吸气剂或打印语句,还是应该以其他方式考虑?

If what I'm doing is using essentially a getter with no constructor, that doesn't make sense to me. 如果我在本质上使用的是没有构造函数的getter,那对我来说就没有意义。 So, I believe it would make more sense from the standpoint of a print statement. 因此,我认为从印刷声明的角度来看会更有意义。 I'm also assuming I don't need to make a new class. 我还假设我不需要上新课。

I think if it was really that easy, the exercise would have been earlier in the textbook: 我认为,如果真的那么简单,那么练习应该早于教科书:

Exercise 129: 练习129:

In the program fragment below, each of the employees in the employee database is stored in an ArrayList. 在下面的程序片段中,员工数据库中的每个员工都存储在ArrayList中。 Complete the program so that the names of all the employees are output. 完成程序,以便输出所有员工的姓名。

public class MainClass
{
  public static void main( String[] args )
  {
    ArrayList<Employee> employees = new ArrayList<Employee>();

employees.add( new Teacher( "Fred Thompkins", 55, 525 ) );
employees.add( new SalesAssistant( "Eric Washington", 7, 72 ) );
employees.add( new Military( "Albert Costa", 236237, "Navy", "Seaman" ) );
employees.add( new Teacher( "Jane Austin", 724, 92 ) );
employees.add( new SalesAssistant( "Jane Black", 91, 295 ) );
employees.add( new Employee( "Scott Black", 23 ) );
employees.add( new SalesPartTime( "Janice Dell", 552, 501, 8.0 ) ); 

    for ( Employee e : employees )

    {



    }

    }
}

It's as simples as that. 就这么简单。 You just have to create a getter for the name, and print it. 您只需要为该名称创建一个吸气剂并打印即可。

for ( Employee e : employees )
{
    System.out.println(e.getName());
}

Alternatively, you can override the toString method of Employee 或者,您可以覆盖EmployeetoString方法

@Override 
public String toString() {
     return this.name;
}

And then, you could call 然后,您可以打电话

for ( Employee e : employees )
{
    System.out.println(e);
}

Looks like you answered your own question. 看来您回答了自己的问题。 You can do this just by getters. 您可以通过吸气剂来做到这一点。 If you have a getName like method in Employee (superclass) class then the below code will work perfectly 如果您在Employee (超类)类中具有类似getName方法,则以下代码将完美运行

for ( Employee e : employees ) {
    System.out.println(e.getName());
}

I actually solved it. 我实际上解决了。 If you click on "show details" in the textbook, it shows you that there's already a "getName" method. 如果单击教科书中的“显示详细信息”,则表明您已经有一个“ getName”方法。 I just needed to call it from the editable part, within the for-loop. 我只需要在for循环中从可编辑部分调用它。

    for ( Employee e : employees )

{
    System.out.println(e.getName());
}

Or something like that. 或类似的东西。

Anyways, that was all that was really needed. 无论如何,这才是真正需要的。 Lol, it was so much more simple than I thought it would be. 大声笑,这比我想象的要简单得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM