Booleans是布爾型基本的實用工具類。
類聲明
以下是com.google.common.primitives.Booleans類的聲明:
@GwtCompatible(emulated=true)
? ?public final class Booleans
? ? ? extends Object
方法
方法繼承
這個類繼承了以下類方法:java.lang.Object
使用所選擇的任何編輯器創建下面的java程序 C:/> Guava
GuavaTester.java
import java.util.List;
import com.google.common.primitives.Booleans;
public class GuavaTester {
public static void main(String args[]){
GuavaTester tester = new GuavaTester();
tester.testBooleans();
}
private void testBooleans(){
boolean[] booleanArray = {true,true,false,true,true,false,false};
//convert array of primitives to array of objects
List<Boolean> objectArray = Booleans.asList(booleanArray);
System.out.println(objectArray.toString());
//convert array of objects to array of primitives
booleanArray = Booleans.toArray(objectArray);
System.out.print("[ ");
for(int i = 0; i< booleanArray.length ; i++){
System.out.print(booleanArray[i] + " ");
}
System.out.println("]");
//check if element is present in the list of primitives or not
System.out.println("true is in list? "+ Booleans.contains(booleanArray, true));
//return the first index of element
System.out.println("true position in list "+ Booleans.indexOf(booleanArray, true));
//Returns the count of true values
System.out.println("true occured: " + Booleans.countTrue());
//Returns the comparisons
System.out.println("false Vs true: " + Booleans.compare(false, true));
System.out.println("false Vs false: " + Booleans.compare(false, false));
System.out.println("true Vs false: " + Booleans.compare(true, false));
System.out.println("true Vs true: " + Booleans.compare(true, true));
}
}
驗證結果
使用javac編譯器編譯如下類
C:\Guava>javac GuavaTester.java
現在運行GuavaTester看到的結果
C:\Guava>java GuavaTester
看到結果
[true, true, false, true, true, false, false]
[ true true false true true false false ]
true is in list? true
true position in list 0
true occured: 0
false Vs true: -1
false Vs false: 0
true Vs false: 1
true Vs true: 0
轉載自并發編程網-ifeve.com