BitSet Example in Java

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - BitSet Example in Java

This Java example program shows a BitSet example in Java.

[edit] Java Source Code

  • Package: example.bitset
  • File: BitOHoney1.java
  1. package example.bitset;
  2.  
  3. import java.util.BitSet;
  4.  
  5. public class BitOHoney1 {
  6.     public static void main(String args[]) {
  7. 	String names[] =
  8. 		{ "Hershey's Kisses", "Nestle's Crunch", "Snickers", "3 Musketeers", "Milky Way", "Twix", "Mr. Goodbar",
  9. 			"Crunchie", "Godiva", "Charleston Chew", "Cadbury's", "Lindt", "Aero", "Hebert", "Toberlone", "Smarties",
  10. 			"LifeSavers", "Riesen", "Goobers", "Raisenettes", "Nerds", "Tootsie Roll", "Sweet Tarts", "Cotton Candy" };
  11. 	BitSet bits = new BitSet();
  12. 	for (int i = 0, n = names.length; i < n; i++) {
  13. 	    if ((names[i].length() % 2) == 0) {
  14. 		bits.set(i);
  15. 	    }
  16. 	}
  17. 	System.out.println(bits);
  18. 	System.out.println("Size  : " + bits.size());
  19. 	System.out.println("Length: " + bits.length());
  20. 	for (int i = 0, n = names.length; i < n; i++) {
  21. 	    if (!bits.get(i)) {
  22. 		System.out.println(names[i] + " is odd");
  23. 	    }
  24. 	}
  25. 	BitSet bites = new BitSet();
  26. 	bites.set(0);
  27. 	bites.set(1);
  28. 	bites.set(2);
  29. 	bites.set(3);
  30. 	bites.andNot(bits);
  31. 	System.out.println(bites);
  32.     }
  33. }

[edit] What Result You Can Get

Run the program, you will get:

{0, 2, 3, 5, 7, 8, 12, 13, 15, 16, 17, 21, 23}
Size  : 64
Length: 24
Nestle's Crunch is odd
Milky Way is odd
Mr. Goodbar is odd
Charleston Chew is odd
Cadbury's is odd
Lindt is odd
Toberlone is odd
Goobers is odd
Raisenettes is odd
Nerds is odd
Sweet Tarts is odd
{1}

[edit] Required External Libraries and/or Files for this Java Example

Need nothing.


[edit] How to Run this Java Example Program

We recommend running this Java example program with Eclipse.

For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.

It's fairly easy.



[edit] Question & Answer

Any question?

Click edit and post your question or answer here.


Personal tools