`
leonzhx
  • 浏览: 785939 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Item 28: Use bounded wildcards to increase API flexibility

阅读更多

1.  While it is counterintuitive that List<String> is not a subtype of List<Object>, it really does make sense. You can put any object into a List<Object>, but you can put only strings into a List<String>.

 

2.  In the following codes, instead of using Iterable<E> , you’d better use Iterable<? extends E>:

public class Stack<E> {
    public Stack();
    public void push(E e);
    public E pop();
    public boolean isEmpty();
    // pushAll method without wildcard type - deficient!
    public void pushAll(Iterable<E> src) {
        for (E e : src)
            push(e);
    }
}

In this way, you are able to pass Iterable<Integer> to Stack<Number> while otherwise you can’t.

 

3.  In the following codes, instead of using Collection <E> , you’d better use Collection <? super E>:

public class Stack<E> {
    public Stack();
    public void push(E e);
    public E pop();
    public boolean isEmpty();
    // Wildcard type for parameter that serves as an E consumer
    public void popAll(Collection<E> dst) {
        while (!isEmpty())
            dst.add(pop());
    }
}

 

In this way, you are able to put pass Collection<Number> to Stack<Integer> while otherwise you can’t.

 

4.  For maximum flexibility, use wildcard types on input parameters that represent producers or consumers. If an input parameter is both a producer and a consumer, then wildcard types will do you no good: you need an exact type match, which is what you get without any wildcards.

 

5.  Do not use wildcard types as return types. Rather than providing additional flexibility for your users, it would force them to use wildcard types in client code.

 

6.  Comparables are always consumers, you should always use Comparable<? super T> in preference to Comparable<T>. The same is true of comparators, you should always use Comparator<? super T> in preference to Comparator<T>. In the following codes:

public static <T extends Comparable<? super T>> T max(List<? extends T> list)

List<ScheduledFuture<?>> scheduledFutures can be passed to the above method while otherwise can’t, ScheduledFuture does not implement Comparable<ScheduledFuture>. Instead, it is a subinterface of Delayed, which extends Comparable<Delayed>.

 

7.  If a type parameter appears only once in a method declaration, replace it with a wildcard. If it’s an unbounded type parameter, replace it with an unbounded wildcard; if it’s a bounded type parameter, replace it with a bounded wildcard.

分享到:
评论

相关推荐

    Effective Java 3rd edition(Effective Java第三版英文原版)附第二版

    Item 31: Use bounded wildcards to increase API flexibility Item 32: Combine generics and varargs judiciously Item 33: Consider typesafe heterogeneous containers 6 Enums and Annotations Item 34: Use ...

    rustracing:用于Rust的OpenTracing API

    生锈 用于Rust的 API。例子 use rustracing :: sampler :: AllSampler;use rustracing :: tag :: Tag;use rustracing :: Tracer;use std :: thread;use std :: time :: Duration;// Creates a tracerlet (span_tx, ...

    原创 QT 5.15.0中Qrand函数更换为QRandomGenerator的问题处理.pdf

    那么,我们可以使用 QRandomGenerator::global()-&gt;bounded(0, 32767) 替换 Qrand 函数,从而解决问题。 在使用 QRandomGenerator 时,需要注意以下几点: * QRandomGenerator 是一个线程安全的随机数生成器,可以...

    rustracing_jaeger:用于Rust的Jaeger跟踪库

    // Creates a tracerlet (span_tx, span_rx) = crossbeam_channel :: bounded ( 10 );let tracer = Tracer :: with_sender (AllSampler, span_tx);{ let span = tracer. span ( "sample_op" ). start (); // Do ...

    Two-Level Segregate Fit

    Although TLSF works rather well in many scenarios, it stands out in applications with hard/soft real-time application which uses explicit memory allocation with high flexibility requirements due to a...

    串行io disruptor

    《Disruptor:高性能的并发数据交换机制》 在构建高效率金融交易平台LMAX的过程中,开发者面临了如何优化数据在并发线程间交换的问题。传统的队列方式在处理并发数据交换时,其延迟成本与磁盘I/O操作相当,这对追求...

    CosmosSQLCalipers:Cosmos SQL API基准测试工具

    CosmosSQLCalipers是一个基本的Cosmos SQL API基准测试实用程序。 它使开发人员可以建模和了解以下参数的影响: 文件尺寸 基于分区键的SELECT查询与点读取 同步与异步API的影响 请求单位(RU)消耗 网络延迟和吞吐...

    FunctionsOfBoundedVariationAndFreeDiscontinuityProblems(Ambrosio)(英文电子书)

    FunctionsOfBoundedVariationAndFreeDiscontinuityProblems(Ambrosio)(英文电子书)

    chan:Rust的多生产者,多消费者并发通道

    此板条箱已达到使用寿命,现在已弃用。 此板条箱的预期后继产品是板条箱。 它的API非常相似,但是有更好的select!... let (s, r) = channel :: bounded ( 100 ); let signals = signal_hook :: ite

    spdlog-master.rar_mpmc_bounded_q.h_spdlog

    标题中的"spdlog-master.rar_mpmc_bounded_q.h_spdlog"暗示了这是一个关于`spdlog`日志库的源代码压缩包,其中包含了`mpmc_bounded_q.h`这个特定的队列数据结构的实现。`spdlog`是一个在C++11环境下广泛使用的高性能...

    Polytope-bounded-Voronoi-diagram-master_QC_wheelgy7_polygrain_gr

    在计算机科学与材料科学的交叉领域,有一种用于模拟和分析多晶材料结构的方法,它涉及到“Polytope-bounded-Voronoi-diagram”(多面体边界Voronoi图)。这个标题中的“master_QC_wheelgy7_polygrain_gr”可能是指一...

    Android中Bounded Service的使用说明.pdf

    在Android开发中,Bounded Service是一种特殊的服务类型,它允许客户端(通常是一个Activity或BroadcastReceiver)与服务建立连接,并通过接口直接交互。Bounded Service的生命周期与客户端紧密关联,当客户端不再...

    ApiNetCore:Api .Net Core com Arquitetura DDD

    **ApiNetCore: 使用.NET Core构建基于领域驱动设计(DDD)的API** 本文将深入探讨如何使用.NET Core框架创建一个遵循领域驱动设计(DDD)原则的API。DDD是一种软件开发方法,强调通过业务领域的专家与开发团队密切...

    如何构建滴滴出行业务中台9 .pdf

    - 架构设计:采用Bounded Context策略,将业务划分为运力供给、收银分账、核心出行等多个领域,降低复杂性。 - 服务化:将核心功能拆分为乘客API、供需撮合、计费出账等服务,提高灵活性和可复用性。 - 异步化:...

    Fast kd-tree Construction with an Adaptive Error-Bounded Heuristic

    为了解决上述问题,本文提出了一种新的构建方法——快速KD树构建算法(Fast kd-tree Construction with an Adaptive Error-Bounded Heuristic),该算法能够在保持较高质量的同时,大幅度提升构建速度,使之适用于...

    英文原版-Hidden Markov Models for Time Series 2nd Edition

    They also provide R code for some of the examples, enabling the use of the codes in similar applications.Effectively interpret data using HMMs This book illustrates the wonderful flexibility of HMMs...

    C Bounded Model Checker.zip

    C Bounded Model Checker(CBMC)是一个开源工具,专门用于静态分析C程序,特别是针对安全性、正确性和可靠性方面的验证。CBMC使用一种称为“有限状态模型检查”的技术,它能够检查程序在有限步执行下的行为,以确定...

    ERP信息化系统:XX SAP _SD510_GTS Bounded Warehouse Operation_APAC_v0.7.pptx

    ERP信息化系统,特别是XX SAP SD510_GTS Bounded Warehouse Operation模块,是针对亚太区(APAC)保税仓库操作的专门解决方案。该系统旨在优化跨国企业的供应链管理,特别是在中国、印度和泰国等国家的保税仓储操作...

Global site tag (gtag.js) - Google Analytics