Results 1 to 2 of 2
Thread: readyOps() method
- 11-04-2010, 11:31 AM #1
Member
- Join Date
- Aug 2010
- Posts
- 67
- Rep Power
- 0
readyOps() method
Hi, I am learning about sockets and SelectionKeys
I have a SelectionKey type variable called key.
I have an if statement of the following:
I understand that this checks to see if the current key is an "accept event".Java Code:if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
The thing I don't get is, why do you have to bother with the method "key.readyOps()" won't it be sufficient to only have:
to make sure that the current selection key is a accept event?Java Code:if (( SelectionKey.OP_ACCEPT == SelectionKey.OP_ACCEPT) {
Why do we have to check if both methods equal SelectionKey.OP_ACCEPT?
Thanks
- 11-04-2010, 04:35 PM #2
readyOps returns an operation set. This means it can have multiple values.
The value of OP_ACCEPT will be some 2^n, which means that it will have only the first bit set to true and the rest to false.
(As an example, 1 is 1 in binary, 2 is 10 in binary, 8 is 1000 in binary, etc.)
This means that you can have a bunch of data contained in a single number. Let's say you have a variable that keeps track of a set of colors in an image. Red is 1, Yellow is 2, Blue is 4, Green is 8, and Pink is 16. In an image that has pink, green, and yellow, you will have a binary number 16+8+2 which is 10000 + 1000 + 10 (in binary), which is 11010.
Now, let's say you want to check if pink is in there. You cannot do "11010 == 10000", because it will be false. Instead, we use the AND operator (a single &, as you see), which keeps only the common bits between the two numbers. In this case, 11010&10000 == 10000. Since that is equal to 10000 (the value of Pink), then it has pink in it.
Let's say instead you want to check for Blue, which is not in the palette. You would do 11010&100, which is 0. Since that's not equal to 100, there is no blue.
This whole process is generally called bit-flagging.
Does that make sense? I'm not sure how much you know about bitwise operators... Here are some more links for you:
Bitwise operation - Wikipedia, the free encyclopedia (bitwise ops)
What are bit flags ? - C++ Forums (bit flagging)
Similar Threads
-
Thread problem, calling method in run method
By majk in forum Threads and SynchronizationReplies: 4Last Post: 09-27-2010, 11:40 AM -
Turning Recursion Method into Iterative method
By mattakuevan in forum New To JavaReplies: 9Last Post: 06-15-2010, 06:46 AM -
method not abstract, does not override actionperformed method.
By Theman in forum New To JavaReplies: 2Last Post: 03-26-2010, 05:12 PM -
ArrayLists compareTo method, equals method
By random0munky in forum New To JavaReplies: 2Last Post: 10-26-2009, 07:20 PM -
Calling a method in a different class from within a method problem
By CirKuT in forum New To JavaReplies: 29Last Post: 09-25-2008, 07:55 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks