Effective Java 26 Favor generic types

时间:2022-09-12 22:00:23

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&period;泛型

    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&period; 不要使用原始类型

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

随机推荐

  1. WIN7 共享网络方法

    WIN7 共享网络方法 第一步: 按WIN+R调出“运行”栏,在“运行”菜单栏输入“cmd”,出现命令提示符,输入命令“netsh wlan set hostednetwork mode=allow ...

  2. 磁盘空间占满inode结点没用完 并删除了文件但是释放不了

    lsof  |grep delete lsof(list system open file )可显示系统打开的文件,以root身份运行. 很多时候文件正在被占用,即使删除了,也无法释放空间,只有停 了 ...

  3. mvc设计模式和mvc框架的区别

    Spring中的新名称也太多了吧!IOC/DI/MVC/AOP/DAO/ORM... 对于刚刚接触spring的我来说确实晕了头!可是一但你完全掌握了一个概念,那么它就会死心塌地的为你服务了.这可比女 ...

  4. Android开发常用的一些第三方网站

    聚合数据-免费数据调用 https://www.juhe.cn/ 有赞- 免费的微商城 http://youzan.com/ 秀米微信图文编辑器 http://xiumi.us/ 禅道项目管理软件 h ...

  5. 史上最全的ASP&period;NET MVC路由配置,以后RouteConfig再弄不懂神仙都难救你啦~

    继续延续坑爹标题系列.其实只是把apress.pro.asp.net.mvc.4.framework里的CHAPTER 13翻译过来罢了,当做自己总结吧.内容看看就好,排版就不要吐槽了,反正我知道你也 ...

  6. Linux(CentOS6&period;4、CentOS6&period;3)下安装、配置PostgreSQL9&period;2

    首先,卸载机器上默认安装的PostgreSQL-8.3.x . [root@localhost ~]# rpm -qa | grep postgresql postgresql-jdbc--.el6. ...

  7. Unable to connect to Redis&semi; nested exception is io&period;lettuce&period;core&period;RedisConnectionException&colon; Unable to connect to &semi;XX&period;XX&period;XX&period;XX&colon;6379&rsqb; with root cause

    java.net.ConnectException: Connection refused: no further information at sun.nio.ch.SocketChannelImp ...

  8. struts拦截器的知识

    如何使用struts2拦截器,或者自定义拦截器.特别注意,在使用拦截器的时候,在Action里面必须最后一定要引用struts2自带的拦截器缺省堆栈defaultStack,如下(这里我是引用了str ...

  9. arcpy导入错误 问题 &OpenCurlyDoubleQuote;ImportError&colon; No module named arcpy”

    如果阁下也出现如下图的错误,用本文的方法也许可以解决问题 首先,打开你python的安装位置,如下图所示的路径,找到desktop10.3.pth文件,打开查看,将你arcgis的相关路径,共3个绝对 ...

  10. learn python the hard way 习题1~5总结

    习题1 print 语句print('Yay! Printing.')print('I "said" do not touch this') 习题2:注释和 # 号 #(octot ...