[Guava源代码阅读笔记]-Basic Utilities篇-1
欢迎訪问:个人博客
写该系列文章的目的是记录Guava源代码中个人感觉不错且值得借鉴的内容。
一、MoreObjects类
//MoreObjects.ToStringHelper类的toString()方法:对于字符串拼接的写法蛮不错的,此前本人一直用比較挫的方式:无论三七二一,先拼接然后再subString()
@Override public String toString() {
// create a copy to keep it consistent in case value changes
boolean omitNullValuesSnapshot = omitNullValues;
String nextSeparator = "";
StringBuilder builder = new StringBuilder(32).append(className)
.append('{');
for (ValueHolder valueHolder = holderHead.next; valueHolder != null;
valueHolder = valueHolder.next) {
if (!omitNullValuesSnapshot || valueHolder.value != null) {
builder.append(nextSeparator);
nextSeparator = ", "; if (valueHolder.name != null) {
builder.append(valueHolder.name).append('=');
}
builder.append(valueHolder.value);
}
}
return builder.append('}').toString();
} private ValueHolder addHolder() {
ValueHolder valueHolder = new ValueHolder();
holderTail = holderTail.next = valueHolder;
return valueHolder;
} private ToStringHelper addHolder(@Nullable Object value) {
ValueHolder valueHolder = addHolder();
valueHolder.value = value;
return this;
} private ToStringHelper addHolder(String name, @Nullable Object value) {
ValueHolder valueHolder = addHolder();
valueHolder.value = value;
valueHolder.name = checkNotNull(name);
return this;
} private static final class ValueHolder {
String name;
Object value;
ValueHolder next;
}
二、Preconditions类
从总体上讲,在使用带有提示消息的相关check方法时须要考虑到性能问题,在一些性能敏感产品中可能。
/*
* All recent hotspots (as of 2009) *really* like to have the natural code
*
* if (guardExpression) {
* throw new BadException(messageExpression);
* }
*
* refactored so that messageExpression is moved to a separate String-returning method.
*
* if (guardExpression) {
* throw new BadException(badMsg(...)); //意思好像是说这样的写法比較影响性能
* }
*
* The alternative natural refactorings into void or Exception-returning methods are much slower.
* This is a big deal - we're talking factors of 2-8 in microbenchmarks, not just 10-20%. (This
* is a hotspot optimizer bug, which should be fixed, but that's a separate, big project).
*
* The coding pattern above is heavily used in java.util, e.g. in ArrayList. There is a
* RangeCheckMicroBenchmark in the JDK that was used to test this.
*
* But the methods in this class want to throw different exceptions, depending on the args, so it
* appears that this pattern is not directly applicable. But we can use the ridiculous, devious
* trick of throwing an exception in the middle of the construction of another exception. Hotspot
* is fine with that.
*/ /**
* Ensures that {@code index} specifies a valid <i>element</i> in an array, list or string of size
* {@code size}. An element index may range from zero, inclusive, to {@code size}, exclusive.
*
* @param index a user-supplied index identifying an element of an array, list or string
* @param size the size of that array, list or string
* @return the value of {@code index}
* @throws IndexOutOfBoundsException if {@code index} is negative or is not less than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static int checkElementIndex(int index, int size) {
return checkElementIndex(index, size, "index");
}
// 但作者在以下的方法中为了实现抛出不同类型的异常时,还是使用了上述所描写叙述的不太OK方式,原因我没太明确。
/**
* Ensures that {@code index} specifies a valid <i>element</i> in an array, list or string of size
* {@code size}. An element index may range from zero, inclusive, to {@code size}, exclusive.
*
* @param index a user-supplied index identifying an element of an array, list or string
* @param size the size of that array, list or string
* @param desc the text to use to describe this index in an error message
* @return the value of {@code index}
* @throws IndexOutOfBoundsException if {@code index} is negative or is not less than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static int checkElementIndex(
int index, int size, @Nullable String desc) {
// Carefully optimized for execution by hotspot (explanatory comment above)
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException(badElementIndex(index, size, desc));
}
return index;
} private static String badElementIndex(int index, int size, String desc) {
if (index < 0) {
return format("%s (%s) must not be negative", desc, index);
} else if (size < 0) {
throw new IllegalArgumentException("negative size: " + size);
} else { // index >= size
return format("%s (%s) must be less than size (%s)", desc, index, size);
}
}
当然,另一个format方法(仍然是字符串处理)
/**
* Substitutes each {@code %s} in {@code template} with an argument. These are matched by
* position: the first {@code %s} gets {@code args[0]}, etc. If there are more arguments than
* placeholders, the unmatched arguments will be appended to the end of the formatted message in
* square braces.
*
* @param template a non-null string containing 0 or more {@code %s} placeholders.
* @param args the arguments to be substituted into the message template. Arguments are converted
* to strings using {@link String#valueOf(Object)}. Arguments can be null.
*/
// Note that this is somewhat-improperly used from Verify.java as well.
static String format(String template, @Nullable Object... args) {
template = String.valueOf(template); // null -> "null" // start substituting the arguments into the '%s' placeholders
StringBuilder builder = new StringBuilder(template.length() + 16 * args.length);
int templateStart = 0;
int i = 0;
while (i < args.length) {
int placeholderStart = template.indexOf("%s", templateStart);
if (placeholderStart == -1) {
break;
}
builder.append(template.substring(templateStart, placeholderStart));
builder.append(args[i++]);
templateStart = placeholderStart + 2;
}
builder.append(template.substring(templateStart)); // if we run out of placeholders, append the extra args in square braces
if (i < args.length) {
builder.append(" [");
builder.append(args[i++]);
while (i < args.length) {
builder.append(", ");
builder.append(args[i++]);
}
builder.append(']');
} return builder.toString();
}
三、Optional及事实上现类
// Optional及其两个实现类Absent,Present。这三个类用简洁的方式攻克了Java中null值的不确定性问题(其设计哲学值得学习)
// public abstract class Optional<T> implements Serializable
// final class Absent<T> extends Optional<T>
// final class Present<T> extends Optional<T>
[Guava源代码阅读笔记]-Basic Utilities篇-1的更多相关文章
- Mongodb源代码阅读笔记:Journal机制
Mongodb源代码阅读笔记:Journal机制 Mongodb源代码阅读笔记:Journal机制 涉及的文件 一些说明 PREPLOGBUFFER WRITETOJOURNAL WRITETODAT ...
- CI框架源代码阅读笔记5 基准測试 BenchMark.php
上一篇博客(CI框架源代码阅读笔记4 引导文件CodeIgniter.php)中.我们已经看到:CI中核心流程的核心功能都是由不同的组件来完毕的.这些组件类似于一个一个单独的模块,不同的模块完毕不同的 ...
- CI框架源代码阅读笔记3 全局函数Common.php
从本篇開始.将深入CI框架的内部.一步步去探索这个框架的实现.结构和设计. Common.php文件定义了一系列的全局函数(一般来说.全局函数具有最高的载入优先权.因此大多数的框架中BootStrap ...
- CI框架源代码阅读笔记2 一切的入口 index.php
上一节(CI框架源代码阅读笔记1 - 环境准备.基本术语和框架流程)中,我们提到了CI框架的基本流程.这里再次贴出流程图.以备參考: 作为CI框架的入口文件.源代码阅读,自然由此開始. 在源代码阅读的 ...
- Spark源代码阅读笔记之DiskStore
Spark源代码阅读笔记之DiskStore BlockManager底层通过BlockStore来对数据进行实际的存储.BlockStore是一个抽象类,有三种实现:DiskStore(磁盘级别的持 ...
- Java Jdk1.8 HashMap源代码阅读笔记二
三.源代码阅读 3.元素包括containsKey(Object key) /** * Returns <tt>true</tt> if this map contains a ...
- [Guava学习笔记]Basic Utilities: Null, 前置条件, Object方法, 排序, 异常
我的技术博客经常被流氓网站恶意爬取转载.请移步原文:http://www.cnblogs.com/hamhog/p/3842433.html,享受整齐的排版.有效的链接.正确的代码缩进.更好的阅读体验 ...
- ruby2.2.2 源代码阅读笔记
这是win32下的结构 从ruby_setup开始阅读 Ruby对象内存结构 RVALUE是一个union,内含ruby所有结构体(RBasic RObject RClass RFloat RStri ...
- 【MySQL】filesort.cc 源代码阅读笔记
最近阅读了部分MySQL排序的代码,把心得记录一下. 参考代码 MySQL: 文件: filesort.cc 函数: filesort() 排序过程伪代码 function filesort(tabl ...
随机推荐
- 常见python快捷键
http://www.cnblogs.com/toutou/p/4778818.html Ctrl+/注释(取消注释)选择的行 Shift + Enter开始新行 Ctrl + Enter智能换行 T ...
- Jupyter Notebook与Jupyterhub的安装与配置
Jupyter Notebook是一个很好用的交互环境,Jupyterhub则在此基础上实现了多用户的管理.最近配置这个环境的时候也遇到了一些坑,想想自己疯狂百度的过程,在此把自己的完整安装配置流程记 ...
- PHP变量的生命周期
变量不仅有其特定的作用范围,还有其存活的周期--生命周期.变量的生命周期指的是变量可被使用的一个时间段,在这个时间段内变量是有效的,一旦超出这个时间段变量就会失效,我们就不能够再访问到该变量的值了. ...
- javascript基础1 语法 点击事件 超链接带点击事件
javascript ----------------------------------------------------------------------------------------- ...
- 【bzoj3307】雨天的尾巴 权值线段树合并
题目描述 N个点,形成一个树状结构.有M次发放,每次选择两个点x,y,对于x到y的路径上(含x,y)每个点发一袋Z类型的物品.完成所有发放后,每个点存放最多的是哪种物品. 输入 第一行数字N,M接下来 ...
- 【Luogu】P2801教主的魔法(分块)
题目链接 激动qwq.这是我A的第一道分块. 分块之后对块内元素暴力sort.修改的时候对于整块打个标记,查询的时候只需要查C-tag就行了 对于非整块,暴力修改,改完之后sort 对于查询……非整块 ...
- Dancing Links 模板
struct dl{ // x: line, y: column struct node{ int c, left, right, up, down; }; vector<node> a; ...
- HDU——1789Doing Homework again(贪心)
Doing Homework again Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Oth ...
- Topcoder SRMCards ——贪心
选择一个数x会删去x+1和x-1,问可以最多选多少次. 显然,对于一段连续的数列,贪心的从左向右选取是最优的. 然后就可以贪心的统计答案了. #include <map> #include ...
- [HAOI2007] 理想的正方形 (单调队列)
题目链接 Solution MD,经过这道题,算是掌握单调队列了... 可以先预处理出点 \((i,j)\) 往上 \(n\) 的最大值和最小值. 然后再横着做一遍单调队列即可. Code #incl ...