Effective Java 27 Favor generic methods
Static utility methods are particularly good candidates for generification.
The type parameter list, which declares the type parameter, goes between the method's modifiers and its return type.
// Generic method
public static <E> Set<E> union(Set<E> s1, Set<E> s2) {
Set<E> result = new HashSet<E> (s1);
result.addAll(s2);
return result;
}
To eliminate redundancy of the type declaration of generic constructor write a generic static factory method corresponding to each constructor that you want to use.
class HashMap<K, V>{
// Generic static factory method
public static <K,V> HashMap<K,V> newHashMap() {
return new HashMap<K,V>();
}
Public static int main(String[] args){
// Parameterized type instance creation with static factory
Map<String, List<String>> anagrams = newHashMap();
}
}
Generic singleton factory pattern
public interface UnaryFunction<T> {
T apply(T arg);
}
// Generic singleton factory pattern
private static UnaryFunction<Object> IDENTITY_FUNCTION =
new UnaryFunction<Object>() {
public Object apply(Object arg) { return arg; }
};
// IDENTITY_FUNCTION is stateless and its type parameter is
// unbounded so it's safe to share one instance across all types
@SuppressWarnings("unchecked")
public static <T> UnaryFunction<T> identityFunction() {
return (UnaryFunction<T>)IDENTITY_FUNCTION;
}
Recursive type bound
// Using a recursive type bound to express mutual comparability
public static <T extends Comparable<T>> T max(List<T> list) {...}
// Returns the maximum value in a list - uses recursive type bound
public static <T extends Comparable<T>> T max(List<T> list) {
Iterator<T> i = list.iterator();
T result = i.next();
while (i.hasNext()) {
T t = i.next();
if (t.compareTo(result) > 0)
result = t;
}
return result;
}
Summary
Generic methods, like generic types, are safer and easier to use than methods that require their clients to cast input parameters and return values. Like types, you should make sure that your new methods can be used without casts, which will often mean making them generic. And like types, you should generify your existing methods to make life easier for new users without breaking existing clients (Item 23).
Effective Java 27 Favor generic methods的更多相关文章
- Effective Java 26 Favor generic types
Use generic types to replace the object declaration Add one or more type parameters to its declarati ...
- Effective Java 16 Favor composition over inheritance
Inheritance disadvantage Unlike method invocation, inheritance violates encapsulation. Since you don ...
- Effective Java 54 Use native methods judiciously
Java Native Interface(JNI) allows Java applications to call native methods, which are special method ...
- Effective Java 76 Write readObject methods defensively
Principle readObject method is effectively another public constructor, and it demands all of the sam ...
- 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 第三版——27. 消除非检查警告
Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...
随机推荐
- Java 常用字符串操作总结
1. String转ASCII码 public static String stringToAscii(String value) { StringBuffer sbu = new StringBuf ...
- Android 学习笔记 BroadcastReceiver广播...
PS:不断提升自己,是件好事... 学习内容: 1.BroadcastReceiver的使用.. 2.通过BroadcastReceiver去启动Service... 1.BroadcastRecei ...
- SQL Server里如何随机记录集
今天的文章,我想给你简单介绍下SQL Server里如何随机记录集. SELECT * FROM Person.Person ORDER BY NEWID() GO 这会引入新的UNIQUEIDENT ...
- 使用aspose.cell动态导出多表头 EXCEL
效果图: 前台调用: using System; using System.Collections.Generic; using System.Linq; using System.Web; usin ...
- C#ASP.NET 通用扩展函数之 IsWhat 简单好用
好东西都需要人去整理.分类 注意:需要引用命名空间 SyntacticSugar 用法: /***扩展函数名细***/ //[IsInRange] int num = 100; //以前写法 if ( ...
- 【转】Python中的GIL、多进程和多线程
转自:http://lesliezhu.github.io/public/2015-04-20-python-multi-process-thread.html 目录 1. GIL(Global In ...
- 重构第30天 尽快返回 (Return ASAP)
理解:把条件语句中复杂的判断用尽快返回来简化. 详解:如首先声明的是前面讲的”分解复杂判断“,简单的来说,当你的代码中有很深的嵌套条件时,花括号就会在代码中形成一个长长的箭头.我们经常在不同的代码中看 ...
- 野比的示波器案例(Winfrom用户控件)
使用该用户控件做的效果图,如果数据正确,可实现 波形.直线.等等效果图...... 对于本程序的认识还是不够深彻.如果有其他方法或算法,欢迎讨论下.将我所能理解的代码都再次标识了一番. ------- ...
- Python on VS Code
install python extension Press F1, and input "ext install python". Then the icon at the le ...
- 多准则决策模型-TOPSIS方法
多准则决策–Multiple Criteria Decision Making 多准则决策–Multiple Criteria Decision Making 多准则决策是指在具有相互冲突.不可共度的 ...