當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Buffer hasRemaining()用法及代碼示例

java.nio.Buffer類的hasRemaining()方法用於判斷當前位置和限製之間是否有任何元素。

用法:

public final boolean hasRemaining()

返回值:當且僅當此緩衝區中至少剩餘一個元素時,此方法才會返回true。


下麵是說明hasRemaining()方法的示例:

範例1:

// Java program to demonstrate 
// hasRemaining() method 
  
import java.nio.*; 
import java.util.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // Declaring the capacity of the ByteBuffer 
        int capacity = 10; 
  
        // creating object of bytebuffer 
        // and allocating size capacity 
        ByteBuffer bb = ByteBuffer.allocate(capacity); 
  
        // putting the value in bytebuffer 
        bb.put((byte)10); 
        bb.put((byte)20); 
        bb.rewind(); 
  
        // Typecast bytebuffer to Buffer 
        Buffer buffer = (Buffer)bb; 
  
        // checking buffer is backed by array or not 
        boolean isRemain = buffer.hasRemaining(); 
  
        // checking if else condition 
        if (isRemain) 
            System.out.println("there is at least one "
                               + "element remaining "
                               + "in this buffer"); 
        else
            System.out.println("there is no "
                               + "element remaining "
                               + "in this buffer"); 
    } 
}
輸出:
there is at least one element remaining in this buffer

範例2:

// Java program to demonstrate 
// hasRemaining() method 
  
import java.nio.*; 
import java.util.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // Declaring the capacity of the ByteBuffer 
        int capacity = 0; 
  
        // creating object of bytebuffer 
        // and allocating size capacity 
        ByteBuffer bb = ByteBuffer.allocate(capacity); 
  
        // Typecast bytebuffer to Buffer 
        Buffer buffer = (Buffer)bb; 
  
        // checking buffer is backed by array or not 
        boolean isRemain = buffer.hasRemaining(); 
  
        // checking if else condition 
        if (isRemain) 
            System.out.println("there is at least one "
                               + "element remaining"
                               + " in this buffer"); 
        else
            System.out.println("there is no "
                               + "element remaining"
                               + " in this buffer"); 
    } 
}
輸出:
there is no element remaining in this buffer

參考: https://docs.oracle.com/javase/9/docs/api/java/nio/Buffer.html#hasRemaining-



相關用法


注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 Buffer hasRemaining() methods in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。