2013年7月25日星期四

Why CharBuffer can be used directly in the abstract method get () and put ()

This post last edited by the flyerttt on 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  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 is an abstract class can not be instantiated, we can only use allocate allocate a buffer, this all know. But jdk documentation CharBuffer the get () method is obviously: 
 public abstract char get () 
 I opened the CharBuffer.java, which really only public abstract char get ();, I do not know in the end is how one thing, it defaults to using the JVM overloaded versions of its public CharBuffer ; get (char [] dst, int offset, int length)? 
 ------ Solution ---------------------------------------- ---- 
 CharBuffer buffer = CharBuffer.allocate (100); 
 System.out.println (buffer.getClass ()); / / to see what 
 ------ Solution ------------- ------------------------------- 
 allocate this method is static, not abstract return type of a CharBuffer The object that is CharBuffer an implementation class only. Like the List subList method that returns an object of type List. 
 ------ For reference only -------------------------------------- - 
 indeed CharBuffer subclass HeapCharBuffer, I use the JDK documentation is old, there is no CharBuffer implementation subclasses, it is time for the next new 
 ------ For reference only --- ------------------------------------ 
 java source code package there, JDK documentation was No, and I checked the latest JDK online documentation nor 
 ------ For reference only ------------------------- -------------- 
 some Java source code included in the category finding out, for example java.io.Bits not only in foreign sites to check online JDK documentation to 

没有评论:

发表评论