private static Iterable<Object> iterable(
final Object first, final Object second, final Object[] rest) {
checkNotNull(rest);
return new AbstractList<Object>() {
@Override
public int size() {
return rest.length + 2;
}
@Override
public Object get(int index) {
switch (index) {
case 0:
return first;
case 1:
return second;
default:
return rest[index - 2];
}
}
};
}
What is author's purpose?
作者的目的是什么?
I guess he wants to make use of the array generated by compiler, rather than new an ArrayList.
我猜他想利用编译器生成的数组,而不是新的ArrayList。
But still a confusing point, why not write as below?
但仍然是一个令人困惑的问题,为什么不写下面的?
private static Iterable<Object> iterable(final Object[] rest) {
checkNotNull(rest);
return new AbstractList<Object>() {
@Override
public int size() {
return rest.length;
}
@Override
public Object get(int index) {
return rest[index];
}
};
}
1 个解决方案
#1
2
The point here is that this method is called from public methods which look like (source):
这里的要点是这个方法是从公共方法调用的,它看起来像(source):
public final String join(
@NullableDecl Object first, @NullableDecl Object second, Object... rest) {
return join(iterable(first, second, rest));
}
Using signatures like this is a trick to force you to pass in at least two arguments - after all, if you've not got two arguments, there is nothing to join.
使用这样的签名是一种强制你传递至少两个参数的技巧 - 毕竟,如果你没有两个参数,就没有什么可以加入的。
For example:
Joiner.on(':').join(); // Compiler error.
Joiner.on(':').join("A"); // Compiler error.
Joiner.on(':').join("A", "B"); // OK.
Joiner.on(':').join("A", "B", "C"); // OK.
// etc.
This iterable
method just creates an Iterable
without having to copy everything into a new array. Doing so would be O(n)
in the number of arguments; the approach taken here is O(1)
.
这个可迭代的方法只需创建一个Iterable,而不必将所有内容复制到一个新数组中。这样做的参数数量为O(n);这里采用的方法是O(1)。
#1
2
The point here is that this method is called from public methods which look like (source):
这里的要点是这个方法是从公共方法调用的,它看起来像(source):
public final String join(
@NullableDecl Object first, @NullableDecl Object second, Object... rest) {
return join(iterable(first, second, rest));
}
Using signatures like this is a trick to force you to pass in at least two arguments - after all, if you've not got two arguments, there is nothing to join.
使用这样的签名是一种强制你传递至少两个参数的技巧 - 毕竟,如果你没有两个参数,就没有什么可以加入的。
For example:
Joiner.on(':').join(); // Compiler error.
Joiner.on(':').join("A"); // Compiler error.
Joiner.on(':').join("A", "B"); // OK.
Joiner.on(':').join("A", "B", "C"); // OK.
// etc.
This iterable
method just creates an Iterable
without having to copy everything into a new array. Doing so would be O(n)
in the number of arguments; the approach taken here is O(1)
.
这个可迭代的方法只需创建一个Iterable,而不必将所有内容复制到一个新数组中。这样做的参数数量为O(n);这里采用的方法是O(1)。