Effective Java 26 Favor generic types
Use generic types to replace the object declaration
- Add one or more type parameters to its declaration.
- Replace all the uses of the type Object with the appropriate type parameter.
- Handle the new E[] errorwith two ways :
- 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];
}
- 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
- You should use boxed primitive types instead of primitive type for the Generic type parameter.
- 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>
- 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的更多相关文章
- Effective Java 27 Favor generic methods
Static utility methods are particularly good candidates for generification. The type parameter list, ...
- Effective Java 16 Favor composition over inheritance
Inheritance disadvantage Unlike method invocation, inheritance violates encapsulation. Since you don ...
- 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 ...
- 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 ...
- 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 ...
- 《Effective Java》读书笔记 - 5.泛型
Chapter 5 Generics Item 23: Don't use raw types in new code 虽然你可以把一个List<String>传给一个List类型(raw ...
- Effective Java 目录
<Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...
- 【Effective Java】阅读
Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...
- Effective Java 第三版——26. 不要使用原始类型
Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...
随机推荐
- HTML5 新特性总结
1.使用autocomplete 自动完成必须给input 加上name. 2.SVG图形代码 复制https://developer.mozilla.org/zh-CN/docs/Web/SVG/E ...
- 《你不知道的javascript》一、函数作用域和块作用域
函数中的作用域 所谓函数作用域,就是属于这个函数的全部变量都可以在整个函数的范围内使用及复用. function foo(a) { var b=a; function bar(c){ var c=b* ...
- MQTT协议学习笔记
1.前沿 万物联网的时代即将到来,物联网也由当初的概念开始进一步落实.随着无线网络技术飞速发展,各种设备都可以连接网络,实现远程控制.例如智能家居最近非常火爆,智能插座.智能LED灯.智能摄像头等.在 ...
- NOIP模拟赛-奶牛晒衣服(dry)
一.奶牛晒衣服(dry) [问题描述] 在熊大妈英明的带领下,时针和它的同伴生下了许多牛宝宝.熊大妈决定给每个宝宝都穿上可爱的婴儿装.于是,为牛宝宝洗晒衣服就成了很不爽的事情. 圣人王担负起了这个重任 ...
- 前端自动化工具 -- Gulp 使用简介
gulp是基于流的前端自动化构建工具. 之前也谈到了 grunt的用法,grunt其实就是配置+配置的形式. 而gulp呢,是基于stream流的形式,也就是前一个函数(工厂)制造出结果,提供后者使用 ...
- thread_Disruptor
转自 知乎 https://zhuanlan.zhihu.com/p/21355046 order从client端传入,decode后进行matching,一旦存在可成交的价格,就要publish到t ...
- 【iOS】线程安全的文件读写
前段时间看了一遍GCD(Grand Central Dispatch)多线程,GCD是苹果为多核开发提供的解决方案 多线程最常见的问题就是读写,比如数据库读写,文件读写,读取是共享的,写是互斥,允许多 ...
- 缺少google api密钥,因此chromium的部分功能将无法使用”的解决办法
使用Chromium时会遇到 "缺少google api密钥,因此chromium的部分功能将无法使用"提示,google了一下 setx Google_API_K ...
- 怎样解决asp.net.mvc上传附件超过长度问题?
最近,在做一个上传附件功能,但是文件超过4M,就报上传的文件超过长度问题
- sql server2008中左连接,右连接,等值连接的区别
数据库中的连接我了解到有left join,right join,inner join这些,以下是它们的区别: 1)左连接(left join):先取出a表的所有数据,再取出a.b表相匹配的数据 2) ...