且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

另一个数组列表到另一个不同类型的数组列表

更新时间:2022-03-30 21:30:32

将对象存储在公共列表中,即使它们具有相同的用法.如果它们具有通用用法,则将此功能划分为一个接口,并通过旨在以相同方式处理的类来实现此接口.使用此接口类型创建一个通用列表,然后在这些接口上执行方法调用:

Store object in a common list just if they have common usage. If they have common usage then partition this functionality into an interface and implement this interface by the classes intended to handle in the same manner. Create a generic list with this interface type and do method calls on the interfaces:

public interface ICommonUsage
{
  public void foo();
  public void bar();
}

public class Class1 implements ICommonUsage
{
  //...
  public void foo() {}
  public void bar() {}
  //...
}

public class Class2 implements ICommonUsage
{
  //...
  public void foo() {}
  public void bar() {}
  //...
}

public class Class3
{
  //...
  private List<ICommonUsage> commonUsedObjects;

  public void commonUsage()
  {
    for ( ICommonUsage item : commonUsedObjects )
    {
      item.foo();
      item.bar();
    }
  }
  //...
}

如果要将对象/接口添加到与其类不兼容的通用列表(它无法调用其上的方法),则编译器会记录一条错误消息.

If you want to add an object/interface to a generic list that is not conform with its class (it hasn't the ability to call the methods on it) the compiler log an error message.