1

I have a method that takes in a List<> and adds all the numbers in the list together and returns if the number is = 100

My problem is that I want to use the same method for a number of different types of lists

So instead of having this

public boolean checkPercent(List<BarStaff> associates){..same..}
public boolean checkPercent(List<Waiters> associates){..same..}
public boolean checkPercent(List<KitchenStaff> associates){..same..} 

I want to have this

public boolean checkPercent(List<could be any type> associates){..same..} 

Instead of reusing the same code just of different lists, is there a way to use the same code for all the different types of lists (the staff have the same values in them so they are not different in any way)?

newSpringer
  • 1,018
  • 10
  • 28
  • 44

4 Answers4

8

You could use a parameterized method:

public <T> boolean checkPercent(List<T> associates)
{
    // snip...
}

or just accept any list:

public boolean checkPercent(List<?> associates)
{
    // snip...
}
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
7

You may create a generic method:

public <T> boolean checkPercent(List<T> associates) {
    ... your code ...
}
Howard
  • 38,639
  • 9
  • 64
  • 83
3

Use generics:

public <T> boolean checkPercent(List<T> associates){...}
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
2

The object-oriented approach would be to have BarStaff, Waiters, and KitchenStaff implement a Employee interface that has a method public int getPercentage().

public boolean checkPercent(List<? extends Employee> associates)
{
    foreach (Employee associate in associates)
    {
        int i = associate.getPercentage();
        // rest of code.
    }
}
Hans Z
  • 4,664
  • 2
  • 27
  • 50
  • I don't think this would work. See http://stackoverflow.com/questions/9810445/listmapstring-string-vs-list-extends-mapstring-string – Eng.Fouad Jul 17 '12 at 15:25
  • Extends and implements are different. – Hans Z Jul 17 '12 at 15:26
  • 2
    This could work if it was an array, i.e `Employee[]` will accept `BarStaff[]`. However, I think the right way to do is `List extends Employee>`. – Eng.Fouad Jul 17 '12 at 15:28