Java – appropriate method for subclassing guava’s immutableset

I have a class

class Receipt
{
     private Set<Order> orders;
     public Receipt(Set<Order> orders)
     {
         this.orders = ImmutableSet.copyOf(orders)
     }   
}

This is very helpful to me

However, due to some types of erasure & the persistence problem I face, I now want to introduce a form

class OrderSet extends Set<Order> {}

Obviously, I can't extend set < order >, because it is an interface I want to keep my implementation immutable However, I cannot extend immutableset < order >, because the document status:

I can use composition to provide a backup set of immutableset for orderset and delegate all set methods to it However, this seems to be a bit over - correction

Is there another way to implement non generic subclasses here?

Solution

No, composition is not overkill, this is the way to go

You should create an orderset as follows, because as Louis emphasized in his comments, this use case is exactly what they mean:

public class OrderSet extends ForwardingSet<Order> {
  private final ImmutableSet<Order> orders;
  public class OrderSet (Set<Order> orders) {
    this.orders = ImmutableSet.copyOf(orders);
  }
  protected ImmutableSet<Order> delegate() { return orders; }
}

The immutable classes in guava are designed not to extend them You must use composition, which is the right way

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>