获取原始类型

尽管 ByteBuffer 只能保存字节类型的数据,但是它具有可以从它所容纳的字节中产生出各
种不同原始类型值的方法。下面这个例子展示了怎样使用这些方法来插入和抽取各种数值:
//: c12:GetData.java
// Getting different representations from a ByteBuffer
import java.nio.*;
import com.bruceeckel.simpletest.*;


public class GetData { 
    private static Test monitor = new Test();
    private static final int BSIZE = 1024;
    public static void main(String[] args) {
    ByteBuffer bb = ByteBuffer.allocate(BSIZE);
        // Allocation automatically zeroes the ByteBuffer:
    int i = 0;
    while(i++ < bb.limit())
      if(bb.get() != 0)
        System.out.println("nonzero");
        System.out.println("i = " + i);
    bb.rewind();
        // Store and read a char array:
    bb.asCharBuffer().put("Howdy!");
    char c;
        while((c = bb.getChar()) != 0)
      System.out.print(c + " ");
    System.out.println();
    bb.rewind();
        // Store and read a short:
    bb.asShortBuffer().put((short)471142);
    System.out.println(bb.getShort());
    bb.rewind();
        // Store and read an int:
    bb.asIntBuffer().put(99471142);
    System.out.println(bb.getInt());
    bb.rewind();
        // Store and read a long:
    bb.asLongBuffer().put(99471142);
    System.out.println(bb.getLong());
    bb.rewind();
        // Store and read a float:
    bb.asFloatBuffer().put(99471142);
    System.out.println(bb.getFloat());
    bb.rewind();
        // Store and read a double:
    bb.asDoubleBuffer().put(99471142);
    System.out.println(bb.getDouble());
    bb.rewind();
    monitor.expect(new String[] {
      "i = 1025",
            "H  o  w  d  y  !  ", 
            "12390", // Truncation changes the value
      "99471142",
      "99471142",
      "9.9471144E7", 
      "9.9471142E7"
        }); 
    } 
} ///:~


在分配一个 ByteBuffer 之后,可以通过检测它的值来查看缓冲器配置是否将其内容自动置
零——它确实是这样做了。这里一共检测了 1024 个值(由缓冲器的 limit()决定),并且
所有的值都是零。


向 ByteBuffer 插入基本类型数据的最简单的方法是:利用 asCharBuffer( )、
asShortBuffer( )等获得该缓冲器上的视图,然后使用视图的 put()方法。我们会发现
此方法适用于所有基本数据类型。仅有一个小小的例外,即使用 ShortBuffer 的 put()
方法时,需要进行类型转换(注意类型转化会截取或改变结果)。而其他所有的视图缓冲器

在使用 put()方法时,不需要进行类型转换。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值