简体   繁体   中英

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. 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:

In the program fragment below, each of the employees in the employee database is stored in an 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

@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

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. I just needed to call it from the editable part, within the for-loop.

    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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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