java类中的多个泛型类型

CKKN

我是 Java 新手,我想知道如何在 Java 中做得更好或更简单、更干净、更简单,比如拥有多个泛型类型的东西

public class Item<T1, T2, T3, T4, T5, T6, T7, T8, T9>{
    private T1 t1;
    private T2 t2;
    private T3 t3;
    private T4 t4;
    private T5 t5;
    private T6 t6;
    private T7 t7;
    private T8 t8;
    private T9 t9;

    public Item(T1 t1){
        this(t1, null, null, null, null, null, null, null, null);
    }
    public Item(T1 t1, T2 t2){
        this(t1, t2, null, null, null, null, null, null, null);
    }

    public Item(T1 t1, T2 t2, T3 t3){
        this(t1, t2, t3, null, null, null, null, null, null);
    }

    public Item(T1 t1, T2 t2, T3 t3, T4 t4){
        this(t1, t2, t3, t4, null, null, null, null, null);
    }
    ...
罗兰

免责声明:(停止投票;-))

这只是一个简单的解决方案,用于保存任意数量的不同类型的对象,这些对象可以由实际类型以一种简单的方式检索,而不保证类型安全。谨慎使用!

建议的解决方案:

你可以只使用一个简单的List<Object>. 由于您不想弄清楚您的实际需求是什么,这可能已经足够了……这是一个示例:

public class Item {
  List<Object> items = new ArrayList<>();

  public <T> Item(T... items) { // well... could also just be Object
     Collections.addAll(this.items, items);
  }

  public <T> T get(int index) {
     return (T) items.get(index); // unsafe of course... but no requirement said something about type safety ;-)
  }

  public static void main(String[] args) {
    Item item = new Item("sum", 123L, 234L, true);

    if (item.get(3)) {
      long sum = item.<Long>get(1) + item.<Long>get(2);
      System.out.println(item.get(0) + " is " + sum);
    }
  }
}

打印:

sum is 357

关于类型安全,您可以通过在检索期间提供类型来改进这一点,如果检索到的对象不是预期的类型,则会失败:

public class Item {
  List<Object> items = new ArrayList<>();

  public <T> Item(T... items) {
    Collections.addAll(this.items, items);
  }

  public <T> T get(int index, Class<T> type) {
    Object item = items.get(index);
    if (type.isInstance(item)) {
      return type.cast(item);
    }
    throw new RuntimeException("failing miserably as index " + index + " isn't of type " + type);
  }

  public static void main(String[] args) {
    Item item = new Item("sum", 123L, 234L, true);

    if (item.get(3, Boolean.class)) {
      long sum = item.get(1, Long.class) + item.get(2, Long.class);
      System.out.println(item.get(0, String.class) + " is " + sum);
    }
  }
}

正如其他人建议的那样:构建器模式也可能有所帮助,但是一旦您添加更多类型或想要删除一些类型,您就需要调整代码。如果你想声明一个变量来保存你的item. 对于此解决方案,这不是必需的。当然,这个解决方案也有一些问题:第一个变体不是类型安全的,可能会导致ClassCastException. RuntimeException如果您想检索没有给定类型的对象,则第二个变体可能会导致,但至少它是类型安全的;-) 所以这实际上取决于您想要完成的任务。

如果您不喜欢RuntimeException第二个变体中的 ,您也可以使用 anOptional代替。我故意省略了该变体,因为它使代码更加冗长。这是get它的实现:

public <T> Optional<T> get(int index, Class<T> type) {
  Object item = items.get(index);
  if (type.isInstance(item)) {
    return Optional.of(type.cast(item));
  }
  return Optional.empty();
}

最后,我可能不会在生产中使用此代码,因为它是一种节省一些代码的解决方法。在生产代码中,我更喜欢类型安全而不是这种简单。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章