java.nio.CharBuffer類的length()方法用於返回此字符緩衝區的長度。從字符序列看時,字符緩衝區的長度就是位置(含)和限製(不含)之間的字符數。也就是說,它等效於remaining()。
用法:
public final int length()
返回值:此方法返回此字符緩衝區的長度。
下麵是說明length()方法的示例:
範例1:
// Java program to demonstrate
// length() method
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Declare and initialize the char array
char[] cb = { 'a', 'b', 'c' };
// wrap the char array into CharBuffer
// using wrap() method
CharBuffer charBuffer = CharBuffer.wrap(cb);
// Get the length of the charBuffer
// using length() method
int length = charBuffer.length();
// print the byte buffer
System.out.println("CharBuffer is:"
+ Arrays.toString(
charBuffer.array())
+ "\nLength:"
+ length);
}
}
輸出:
CharBuffer is:[a, b, c] Length:3
範例2:
// Java program to demonstrate
// length() method
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// defining and allocating CharBuffer
// using allocate() method
CharBuffer charBuffer
= CharBuffer.allocate(4);
// append char value in charBuffer
// using append() method
charBuffer.append('a');
charBuffer.append('b');
// print the char buffer
System.out.println("CharBuffer before append:"
+ Arrays.toString(
charBuffer.array())
+ "\nLength:"
+ charBuffer.length());
// append char value in charBuffer
// using append() method
charBuffer.append('c');
// print the char buffer
System.out.println("\nCharBuffer after append:"
+ Arrays.toString(
charBuffer.array())
+ "\nLength:"
+ charBuffer.length());
}
}
輸出:
CharBuffer before append:[a, b,, ] Length:2 CharBuffer after append:[a, b, c, ] Length:1
參考: https://docs.oracle.com/javase/9/docs/api/java/nio/CharBuffer.html#length-
相關用法
- Java CharBuffer flip()用法及代碼示例
- Java CharBuffer order()用法及代碼示例
- Java CharBuffer position()用法及代碼示例
- Java CharBuffer reset()用法及代碼示例
- Java CharBuffer rewind()用法及代碼示例
- Java CharBuffer subSequence()用法及代碼示例
- Java CharBuffer read()用法及代碼示例
- Java CharBuffer mark()用法及代碼示例
- Java CharBuffer clear()用法及代碼示例
- Java CharBuffer append()用法及代碼示例
- Java CharBuffer charAt()用法及代碼示例
- Java CharBuffer limit()用法及代碼示例
- Java CharBuffer chars()用法及代碼示例
- Java CharBuffer get()用法及代碼示例
- Java CharBuffer put()用法及代碼示例
注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 CharBuffer length() methods in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。