为什么Java中的泛型使用类而不是基本类型?
例如,这工作正常:
List<Integer> foo = new ArrayList<Integer>();
Run Code Online (Sandbox Code Playgroud)
但这是不允许的:
List<int> bar = new ArrayList<int>();
Run Code Online (Sandbox Code Playgroud) 高度重复的代码通常是一件坏事,并且有一些设计模式可以帮助减少这种情况.然而,由于语言本身的限制,有时它是不可避免的.以下示例来自java.util.Arrays:
/**
* Assigns the specified long value to each element of the specified
* range of the specified array of longs. The range to be filled
* extends from index <tt>fromIndex</tt>, inclusive, to index
* <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the
* range to be filled is empty.)
*
* @param a the array to be filled
* @param fromIndex the index of the first element (inclusive) to be
* filled with the specified value
* @param toIndex …Run Code Online (Sandbox Code Playgroud) 我需要对各种原始类型执行算法; 算法基本相同,但变量的类型除外.所以,例如,
/**
* Determine if <code>value</code> is the bitwise OR of elements of <code>validValues</code> array.
* For instance, our valid choices are 0001, 0010, and 1000.
* We are given a value of 1001. This is valid because it can be made from
* ORing together 0001 and 1000.
* On the other hand, if we are given a value of 1111, this is invalid because
* you cannot turn on the second bit from left by ORing together …Run Code Online (Sandbox Code Playgroud) 位输入流由字节数组支持。有一些方法可以从该字节数组读取到各种强制原始数组。
有重复的代码。Java 缺乏原始类型的泛型,因此重复可能是不可避免的。
重复代码在以下方法中很明显:
@Override
public long readBytes(final byte[] out, final int offset, final int count, final int bits) {
final int total = offset + count;
assert out != null;
assert total <= out.length;
final long startPosition = position();
for (int i = offset; i < total; i++) {
out[i] = readByte(bits);
}
return position() - startPosition;
}
@Override
public long readShorts(final short[] out, final int offset, final int count, final int bits) {
final int …Run Code Online (Sandbox Code Playgroud)