相关疑难解决方法(0)

线程“main”中的异常 java.lang.NoSuchMethodError: java.nio.ByteBuffer.flip()Ljava/nio/ByteBuffer

我有一个方法如下,它已经正常运行了很长时间:

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)

java bytebuffer java-8 java-11

29
推荐指数
1
解决办法
1万
查看次数

Cloneable#clone 方法不必要的强制转换

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而不是它自己?

java java-8

2
推荐指数
1
解决办法
88
查看次数

标签 统计

java ×2

java-8 ×2

bytebuffer ×1

java-11 ×1