zoukankan      html  css  js  c++  java
  • 位集合类BitSet

    位集合类中封装了有关一组二进制数据的操作。

    我们先来看一下例8.6 BitSetApp.java。

    例8.6 BitSetApp.java

    //import java.lang.*;

    import java.util.BitSet;

    public class BitSetApp{

    private static int n=5;

    public static void main(String[] args){

    BitSet set1=new BitSet(n);

    for(int i=0;i<N;I++)&NBSP;SET1.SET(I);

    //将set1的各位赋1,即各位均为true

    BitSet set2= new BitSet();

    set2=(BitSet)set1.clone();

    //set2为set1的拷贝

    set1.clear(0);

    set2.clear(2);

    //将set1的第0位set2的第2位清零

    System.out.println("The set1 is: "+set1);

    //直接将set1转换成字符串输出,输出的内容是set1中值true所处的位置

    //打印结果为The set1 is:{1,2,3,4}

    System.out.println("The hash code of set2 is: "+set2.hashCode());

    //打印set2的hashCode

    printbit("set1",set1);

    printbit("set2",set2);

    //调用打印程序printbit(),打印对象中的每一个元素

    //打印set1的结果为The bit set1 is: false true true true true

    set1.and(set2);

    printbit("set1 and set2",set1);

    //完成set1 and set2,并打印结果

    set1.or(set2);

    printbit("set1 or set2",set1);

    //完成set1 or set2,并打印结果

    set1.xor(set2);

    printbit("set1 xor set2",set1);

    //完成set1 xor set2,并打印结果

    }

    //打印BitSet对象中的内容

    public static void printbit(String name,BitSet set){

    System.out.print("The bit "+name+" is: ");

    for(int i=0;i<N;I++)

    System.out.print(set.get(i)+" ");

    System.out.println();

    }

    }

    运行结果:

    The set1 is: {1, 2, 3, 4}

    The hash code of set2 is: 1225

    The bit set1 is: false true true true true

    The bit set2 is: true true false true true

    The bit set1 and set2 is: false true false true true

    The bit set1 or set2 is: true true false true true

    The bit set1 xor set2 is: false false false false false

    程序中使用了BitSet类提供的两种构造方法:

    public BitSet();

    public BitSet(int n);

    参数n代表所创建的BitSet类的对象的大小。BitSet类的对象的大小在必要时会由系统自动扩充。

    其它方法:

    public void set(int n)

    将BitSet对象的第n位设置成1。

    public void clear(int n)

    将BitSet对象的第n位清零。

    public boolean get(int n)

    读取位集合对象的第n位的值,它获取的是一个布尔值。当第n位为1时,返回true;第n位为0时,返回false。

    另外,如在程序中所示,当把一BitSet类的对象转换成字符串输出时,输出的内容是此对象中true所处的位置。

    在BitSet中提供了一组位操作,分别是:

    public void and(BitSet set)

    public void or(BitSet set)

    public void xor(BitSet set)

    利用它们可以完成两个位集合之间的与、或、异或操作。

    BitSet类中有一方法public int size()来取得位集合的大小,它的返回值与初始化时设定的位集合大小n不一样,一般为64。

     

  • 相关阅读:
    nyoj 311 完全背包
    nyoj 737 石子合并(一)
    nyoj 232 How to eat more Banana
    nyoj 456 邮票分你一半
    nyoj 236 心急的C小加
    nyoj 195 飞翔
    nyoj 201 作业题
    SOS 调试扩展 (SOS.dll)
    使用Windbg和SoS扩展调试分析.NET程序
    windbg命令分类与概述
  • 原文地址:https://www.cnblogs.com/borter/p/9434167.html
Copyright © 2011-2022 走看看