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年出版,到现在已经将 ...
随机推荐
- SQL Server里强制参数化的痛苦
几天前,我写了篇SQL Server里简单参数化的痛苦.今天我想继续这个话题,谈下SQL Server里强制参数化(Forced Parameterization). 强制参数化(Forced Par ...
- An Introduction to Garbage Collection(垃圾回收简介)
1. Introduction 2. Principles 3. Advantages 4. Disadvantages 5. 常见的垃圾回收技术 5.1. 跟踪式垃圾回收 5.1.1. 基本算法 5 ...
- 2015年百度之星初赛(1) --- A 超级赛亚ACMer
超级赛亚ACMer Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Problem D ...
- Linq专题之对象初始化器
在C#3.0之前,如果创建一个新的对象,往往需要调用类的构造函数来初始化该对象的值,在c#3.0提供了一个"对象初始化器"的机制,使得开发人员在创建新的对象时不通过调用类的构造函数 ...
- c# Graphics使用方法(画圆写字代码)
画填充圆: Graphics gra = this.pictureBox1.CreateGraphics(); gra.SmoothingMode = System.Drawing.Drawing2D ...
- RSA密钥——JAVA与C#的区别和联系
PS:好久没写博了,最近在考虑以后的事情,而且手上杂事也比较多,终于得空来写两篇. 首先感谢:http://www.codeproject.com/Articles/25487/Cryptogra ...
- ASP.NET或WinFrom中获取汉子的拼音首字母
1.获得一个字符串的每个字的拼音首字母构成所需的字符串 #region 获取首字母 /// <summary> /// 这个办法是用来获得一个字符串的每个字的拼音首字母构 ...
- [moka同学笔记]yii2.0 dropdownlist的简单使用(一)
1.controller控制中 $modelCountrytelCode = CountryTelCode::find()->orderBy('id DESC')->all(); $tel ...
- SQL Server 全局变量
SQL Server中所有全局变量都使用两个@符号作为前缀 --1.@@error 最后一个T-SQL错误的错误号(目的是或得违反约束的错误号) insert into Subject values( ...
- Linux下建立Nexus私服
Linux下建立Nexus私服 要安装3个东西,然后配置私服: 1.JDK 2.Maven 3.Nexus 然后配置 1.JDK的安装 下载JDK安装包,格式为RPM格式,安装即可 安装程序 #rpm ...