【问题标题】:Create list with different objects创建具有不同对象的列表
【发布时间】:2012-07-16 13:24:35
【问题描述】:

我有一个方法接受List<> 并将列表中的所有数字加在一起,如果数字= 100 则返回

我的问题是我想对许多不同类型的列表使用相同的方法

所以不要有这个

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

我想要这个

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

除了重复使用不同列表的相同代码之外,有没有办法对所有不同类型的列表使用相同的代码(员工在其中具有相同的值,因此它们没有任何不同)?

【问题讨论】:

    标签: java list


    【解决方案1】:

    你可以使用parameterized method:

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

    或者只是accept any list:

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

    【讨论】:

      【解决方案2】:

      你可以创建一个generic method:

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

      【讨论】:

        【解决方案3】:

        使用泛型:

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

        【讨论】:

          【解决方案4】:

          面向对象的方法是让BarStaffWaitersKitchenStaff 实现具有public int getPercentage() 方法的Employee 接口。

          public boolean checkPercent(List<? extends Employee> associates)
          {
              foreach (Employee associate in associates)
              {
                  int i = associate.getPercentage();
                  // rest of code.
              }
          }
          

          【讨论】:

          • 我认为这行不通。见stackoverflow.com/questions/9810445/…
          • 扩展和实现不同。
          • 如果它是一个数组,这可以工作,即Employee[] 将接受BarStaff[]。但是,我认为正确的做法是List&lt;? extends Employee&gt;
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-01-13
          • 2012-06-19
          • 1970-01-01
          • 2018-05-01
          • 2017-12-30
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多