日期:2014-05-20  浏览次数:20727 次

为什么可以直接使用CharBuffer中的抽象方法get()和put()
本帖最后由 flyerttt 于 2013-07-24 21:53:55 编辑
import  java.nio.CharBuffer;

public class BufferTest{
    private static int  index = 0;
    private static String[] strings = {
        "A random string value",
        "The product of an infinite number of monkeys",
        "Hey hey we're the Monkees",
        "Opening act for the Monkees: Jimi Hendrix",
        "'Scuse me while I kiss this fly'",
        "Help Me! Help Me!"
    };
    private static void  drainBuffer(CharBuffer buffer){
        while (buffer.hasRemaining()){
            System.out.print(buffer.get());
        }
        System.out.println();
    }
    private static boolean fillBuffer(CharBuffer buffer){
        if ( index >= strings.length)  return false ;
            String string=strings[index++];
        for (int i=0;i<string.length();i++)
            buffer.put(string.charAt(i));
        return true ;
    }
    public static void   main(String args[])  throws  Exception{
        CharBuffer buffer = CharBuffer.allocate (100);
        while (fillBuffer(buffer)){
            buffer.flip();
            drainBuffer (buffer);
            buffer.clear();
        }
    }
}


CharBuffer是抽象类不能实例化,所以只能用allocate分配缓冲区,这个都知道。但是jdk文档里CharBuffer的get()方法明明是: