Use generic types to replace the object declaration

  1. Add one or more type parameters to its declaration.
  2. Replace all the uses of the type Object with the appropriate type parameter.
  3. Handle the new E[] errorwith two ways :
    1. Use the explicit type casting in the constructor. And use @SuppressWarnings("unchecked") to suppress warning.

      // The elements array will contain only E instances from push(E).

      // This is sufficient to ensure type safety, but the runtime

      // type of the array won't be E[]; it will always be Object[]!

      @SuppressWarnings("unchecked")

      public Stack() {

      elements = (E[]) new Object[DEFAULT_INITIAL_CAPACITY];

      }

    2. Change the type of the field elements from E[]to Object[] and explicitly cast the popped element type to E.

      private Object[] elements;

      public Stack() {

      elements = new Object[DEFAULT_INITIAL_CAPACITY];

      }

      // Appropriate suppression of unchecked warning

      public E pop() {

      if (size==0)

      throw new EmptyStackException();

      // push requires elements to be of type E, so cast is correct

      @SuppressWarnings("unchecked") E result = (E) elements[--size];

      elements[size] = null; // Eliminate obsolete reference

      return result;

      }

/**

* @author kaibo

*

*/

// Object-based collection - a prime candidate for generics

public class Stack<E> {

private E[] elements;

private int size = 0;

private static final int DEFAULT_INITIAL_CAPACITY = 16;

public Stack() {

elements = (E[]) new Object[DEFAULT_INITIAL_CAPACITY];

}

public void push(E e) {

ensureCapacity();

elements[size++] = e;

}

public E pop() {

if (size == 0)

throw new EmptyStackException();

E result = elements[--size];

elements[size] = null; // Eliminate obsolete reference

return result;

}

// no changes in isEmpty or ensureCapacity

private void ensureCapacity() {

if (elements.length == size)

elements = Arrays.copyOf(elements, 2 * size + 1);

}

public static void main(String[] args) {

Stack<Integer> s = new Stack<Integer>();

s.push(1);

s.push(2);

s.push(3);

System.out.println(s);

}

}

Note

  1. You should use boxed primitive types instead of primitive type for the Generic type parameter.
  2. There are some generic types that restrict the permissible values of their type parameters. For example, consider java.util.concurrent.DelayQueue, whose declaration looks like this:

    class DelayQueue<E extends Delayed> implements BlockingQueue<E>

    The type parameter E is known as a bounded type parameter. Note that the subtype relation is defined so that every type is a subtype of itself [JLS, 4.10], so it is legal to create a DelayQueue<Delayed>

  3. Generify your existing types as time permits. This will make life easier for new users of these types without breaking existing clients.

Summary

Generic types are safer and easier to use than types that require casts in client code. When you design new types, make sure that they can be used without such casts. This will often mean making the types generic. Generify your existing types as time permits. This will make life easier for new users of these types without breaking existing clients (Item 23).

Effective Java 26 Favor generic types的更多相关文章

  1. Effective Java 27 Favor generic methods

    Static utility methods are particularly good candidates for generification. The type parameter list, ...

  2. Effective Java 16 Favor composition over inheritance

    Inheritance disadvantage Unlike method invocation, inheritance violates encapsulation. Since you don ...

  3. Effective Java 49 Prefer primitive types to boxed primitives

    No. Primitives Boxed Primitives 1 Have their own values Have identities distinct from their values 2 ...

  4. Effective Java 60 Favor the use of standard exceptions

    Benefits to reuse preexisting exceptions It makes your API easier to learn and use. Programs using y ...

  5. Effective Java Index

    Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...

  6. 《Effective Java》读书笔记 - 5.泛型

    Chapter 5 Generics Item 23: Don't use raw types in new code 虽然你可以把一个List<String>传给一个List类型(raw ...

  7. Effective Java 目录

    <Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...

  8. 【Effective Java】阅读

    Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...

  9. Effective Java 第三版——26. 不要使用原始类型

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

随机推荐

  1. JS数组追加数组采用push.apply的坑

    JS数组追加数组没有现成的函数,这么多年我已经习惯了a.push.apply(a, b);这种自以为很酷的,不需要写for循环的写法,一直也没遇到什么问题,直到今天我要append的b是个很大的数组时 ...

  2. HQueue:基于HBase的消息队列

    HQueue:基于HBase的消息队列   凌柏   ​1. HQueue简介 HQueue是一淘搜索网页抓取离线系统团队基于HBase开发的一套分布式.持久化消息队列.它利用HTable存储消息数据 ...

  3. springMVC源码分析之拦截器

    一个东西用久了,自然就会从仅使用的层面上升到探究其原理的层面,在javaweb中springmvc更是如此,越是优秀的框架,其底层实现代码更是复杂,而在我看来,一个优秀程序猿就相当于一名武林高手,不断 ...

  4. SQL Server 诊断查询-(1)

    Query #1 is Version Info. SQL and OS Version information for current instance SELECT @@SERVERNAME AS ...

  5. Unity多语言本地化改进版

    简介 之前捣鼓过一个通过csv配置游戏多语言支持的小工具,但是发现使用过程中,通过notepad++去进行转码很不方便,并且直接将配置的csv不加密的放在游戏中心里感觉不是很踏实 于是乎~~ 新的方案 ...

  6. WebService服务调用方法介绍

    1 背景概述 由于在项目中需要多次调用webservice服务,本文主要总结了一下java调用WebService常见的6种方式,即:四种框架的五种调用方法以及使用AEAI ESB进行调用的方法. 2 ...

  7. 【ASP.NET MVC 】让@Ajax.ActionLink获取的数据不进Cache

    刚玩这个东西的时候,发现IE会进Cache,不管怎么删除,修改,后台删除了,前台还是一样,找了一下,HTML5只提供了 <meta http-equiv="pragma" c ...

  8. 外表cms,内在wiki的系统anwiki

    比较完整面向对象的语法格式,     外表cms,内在wiki的系统   http://enanocms.org/features   比较老,php4的语法

  9. hibernate3 Duplicate class/entity mapping(异常)

    hibernate3 Duplicate class/entity mapping(异常) 代码:      Configuration config = new Configuration().ad ...

  10. hdu 2952 Counting Sheep

    本题来自:http://acm.hdu.edu.cn/showproblem.php?pid=2952 题意:上下左右4个方向为一群.搜索有几群羊 #include <stdio.h> # ...