43、考虑方法public static T[] repeat(int n, T obj, IntFunction constr)。调用Arrays.repeat(10, 42, int[]::new)会失败。为什么?如何修复?对于其他基本类型需要做什么?
调用 Arrays.repeat(10, 42, int[]::new) 失败是因为泛型类型参数 T 不能是基本类型,而 int 是基本类型。
修复方法是使用对应的包装类型,如 Integer 。
对于其他基本类型,也需要使用它们对应的包装类型,如:
-
Byte -
Short -
Long -
Float -
Double -
Character -
Boolean
44、考虑方法 public static <T> ArrayList<T> repeat(int n, T obj) ,该方法能构造一个包含 T 值的 ArrayList<T> 。能否不使用 Class 值或构造函数引用,从该 ArrayList 中生成一个 T[] 数组?如果不能,原因是什么?
不能。因为在Java中,泛型是在编译时进行类型擦除的,运行时无法获取泛型的具体类型信息。而创建数组时需要明确知道数组元素的具体类型,不使用 Class 值或构造函数引用就无法确定 T 的具体类型,因此不能创建 T[] 数组。
45、实现方法 @SafeVarargs public static final <T> T[] repeat(int n, T... objs) ,返回一个包含给定对象 n 份副本的数组。注意,由于可以通过反射扩展 objs ,因此不需要 Class 值或构造函数引用。
以下是该方法的实现:
import java.lang.reflect.Array;
public class Main {
@SafeVarargs
public static final <T> T[] repeat(int n, T... objs) {
T[] result = (T[]) Array.newInstance(objs.getClass().getComponentType(), n * objs.length);
for (int i = 0; i < n; i++) {
System.arraycopy(objs, 0, result, i * objs.length, objs.length);
}
return result;
}
}
46、改进方法 public static <V, T extends Throwable> V doWork(Callable<V> c, T ex) throws T ,使得不必传入可能永远不会被使用的异常对象。相反,接受异常类的构造函数引用。
可将原方法修改为接受异常类的构造函数引用,以下是改进后的示例代码:
import java.util.concurrent.Callable;
public class Main {
public static <V, T extends Throwable> V doWork(Callable<V> c, java.util.function.Supplier<T> exceptionSupplier) throws T {
try {
return c.call();
} catch (Throwable realEx) {
T ex = exceptionSupplier.get();
ex.initCause(realEx);
throw ex;
}
}
}
此代码中, doWork 方法接受一个 Callable<V> 和一个 Supplier<T> , Supplier<T> 为异常类的构造函数引用。在捕获到异常时,使用该构造函数引用创建异常对象并抛出。
47、实现“埃拉托斯特尼筛法”算法来确定所有小于等于n的质数。将从2到n的所有数字添加到一个集合中。然后反复找出集合中最小的元素s,并移除s²、s · (s + 1)、s · (s + 2)等等。当s² > n时,筛选结束。分别使用HashSet 和BitSet来实现该算法。
以下是使用 Java 实现埃拉托斯特尼筛法的代码,分别使用了 HashSet<Integer> 和 BitSet :

最低0.47元/天 解锁文章
398

被折叠的 条评论
为什么被折叠?



