我有一个方法如下,它已经正常运行了很长时间:
private String loadFromFile(){
RandomAccessFile inFile = null;
FileChannel inChannel = null;
StringBuilder sb = new StringBuilder();
try {
inFile = new RandomAccessFile(this.latestImageFile, "r");
inChannel = inFile.getChannel();
ByteBuffer bb = ByteBuffer.allocate(2046);
while( inChannel.read(bb) != -1){
bb.flip();
while(bb.hasRemaining()){
char c = (char) bb.get(); // read character at current position and set the pointer to current position + 1
sb.append(c);
}
bb.clear();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inChannel != null) try {inChannel.close(); } catch (IOException e){} …Run Code Online (Sandbox Code Playgroud) class MyCls implements Cloneable {
@Override
protected MyCls clone() throws CloneNotSupportedException {
return new MyCls(//...
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码没有任何问题。那么为什么CopyOnWriteArrayList#clone返回一个Object而不是CopyOnWriteArrayList?从转换回Object所需类型时,编译器会哭。毕竟,这个设计决定的原因是什么?我看到整个图书馆都在重复这种模式。
Ralph建议下面的代码是有效的,而不是上面的代码:
@Override MyCls clone() throws CloneNotSupportedException {
MyCls clone = (MyCls)super.clone();
clone.x = this.x; //or what ever to do return clone
// ...
}
Run Code Online (Sandbox Code Playgroud)
问题还是一样。为什么CopyOnWriteArrayList#clone返回Object而不是它自己?