What's the easiest way to bind a range value in Java?

I have a numeric value myX that I want to associate with some range [X_MIN, X_MAX]. I don't care if myX is in this range or not, I just want to do it.

Obviously this works:

if(myX < X_MIN) {
  myX = X_MIN;
} else if (myX > X_MAX) {
  mX = X_MAX;
}

      

how does it do:

myX = Math.max(X_MIN, Math.min(myX, X_MAX));

      

The first is too wordy, and the meaning of the second is not immediately obvious. Is there another easy, explicit way to do this? Solutions using Guava, Commons, etc. are greatly appreciated.

+3


source to share





All Articles