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. node log4js包

    http://blog.csdn.net/heiantianshi1/article/details/43984601

  2. [linux]执行pip安装的程序:command not found

    执行pip安装的程序:command not found 问题描述: 我有一台阿里云服务器,上面装的是centos系统,我用pip安装好vituralenv,都没办法直接启动.同样 我今天在部署我的t ...

  3. JS基础---->js中ajax的使用

    AJAX 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术.今天我们就简单的学习一下ajax的使用及过程. ajax的使用 先贴出大致的代码,是请求本地的一个servlet,返回json格 ...

  4. WebGL on iOS8 终于等到了这一天

    WWDC2014刚结束,这次的大会是名符其实的开发者大会,更贴切的应该说的确是一次软件开发者的大会,对于OSX和iOS的更多功能特性让人兴奋,Swift新语言促成了如上图片 但我更感兴趣的是WebGL ...

  5. iOS实现书架布局样式【一些电子书的首页】

    本文实现了类似电子书首页,用来展示图书或小说的布局页面,书架列表[iPhone6模拟器],屏幕尺寸还没进行适配,只是做个简单的demo[纯代码实现方式] 实现采用的是UICollectionView和 ...

  6. Gradle学习系列之四——增量式构建

    在本系列的上篇文章中,我们讲到了如何读懂Gradle的语法,在本篇文章中,我们将讲到增量式地构建项目. 请通过以下方式下载本系列文章的Github示例代码: git clone https://git ...

  7. MVC ,Action方法传数据给视图有几种方式?--PS:tempData和Viewbag,还有ViewData之间的区别

    //---------------------------------控制器向视图传递数据 public ActionResult TransData() { //1.ViewBag ViewBag. ...

  8. jquery1.9+获取append后的动态元素

    jquery 1.9+放弃了live,说是用on代替了! 那么如果我们以前用live来获取jquery动态添加的元素,现在应该用on怎么写呢? 首先: <div id="one&quo ...

  9. 解决android引用library project错误

    在andriod项目中引用另一个library project时,报 The container 'Android Dependencies' references non existing libr ...

  10. WebApi传参总动员(五)

    上回说到涉及多个实体的传参,用常规的方法已经不能解决了.这回我们用终极大招搞定她. WebApi:注意要引用JSON.Net [HttpPost] public string GetData(stri ...