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的更多相关文章

  1. Effective Java 26 Favor generic types

    Use generic types to replace the object declaration Add one or more type parameters to its declarati ...

  2. Effective Java 16 Favor composition over inheritance

    Inheritance disadvantage Unlike method invocation, inheritance violates encapsulation. Since you don ...

  3. Effective Java 54 Use native methods judiciously

    Java Native Interface(JNI) allows Java applications to call native methods, which are special method ...

  4. Effective Java 76 Write readObject methods defensively

    Principle readObject method is effectively another public constructor, and it demands all of the sam ...

  5. 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 ...

  6. 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 ...

  7. 《Effective Java》读书笔记 - 5.泛型

    Chapter 5 Generics Item 23: Don't use raw types in new code 虽然你可以把一个List<String>传给一个List类型(raw ...

  8. Effective Java 目录

    <Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...

  9. Effective Java 第三版——27. 消除非检查警告

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

随机推荐

  1. ASP.NET MVC和WebForm 轻松实现前端和后端的双重验证 jquery.validate+ValidationSugar

    上次不足的改进 可能上一个贴子给大家带来很多误解,所以我这次把DEMO完善了两个版本 [ASP.NET WEBFROM]和[ ASP.NET MVC] 修改了一些BUG,并且修改了一些细了 在上个贴子 ...

  2. 重构第30天 尽快返回 (Return ASAP)

    理解:把条件语句中复杂的判断用尽快返回来简化. 详解:如首先声明的是前面讲的”分解复杂判断“,简单的来说,当你的代码中有很深的嵌套条件时,花括号就会在代码中形成一个长长的箭头.我们经常在不同的代码中看 ...

  3. C#检查标准图幅编号

    /// <summary> /// 检查是否为标准图幅编号 /// </summary> /// <param name="MapNumber"> ...

  4. KTV点歌系统

    经过十多天的艰苦奋战,MyKTV点歌系统终于成型,从刚开始接到项目的茫然,到完成项目时的喜悦,整个过程的艰辛和付出只有自己知道.虽然这个项目还有许多需要完善的地方,譬如添加歌词信息,实现窗体的美化等, ...

  5. [moka同学笔记]yii2 activeForm 表单样式的修改(二)

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAABAEAAANXCAIAAADLkdErAAAgAElEQVR4nOzdfWwc953nef6zwO5Zg8

  6. No.011:Container With Most Water

    问题: Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, a ...

  7. maven oracle jdbc jar

    1.problem describe: when your dependency jar about oracle use code like this: <!-- oracle-connect ...

  8. XML的约束(schema)

    XML Schema也是一种用于定义和描述XML文档结构与内容的模式语言,其出现是为了克服DTD的局限性 XML Schema符合XML语法结构 DOM.SAX等XML API很容易解析出XML Sc ...

  9. swift学习笔记之-函数

    //函数 import UIKit /*获得系统时间 var date = NSDate() var timeFormatter = NSDateFormatter() timeFormatter.d ...

  10. AloneJs.confirmbox() —— 确认框

    一.引用 <link href="https://cdn.suziyun.com/alonejs.min.css" rel="stylesheet" /& ...