Java CharBuffer length()方法及示例

Java CharBuffer length()方法及示例

java.nio.CharBuffer类length() 方法是用来返回这个字符缓冲区的长度。当被看作是一个字符序列时,一个字符缓冲区的长度只是在位置(包括)和极限(不包括)之间的字符数;也就是说,它等同于剩余()。

语法

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-

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

Java 参考指南