简体   繁体   中英

Create list with different objects

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

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

You may create a generic method :

public <T> boolean checkPercent(List<T> associates) {
    ... your code ...
}

使用泛型:

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

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

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