Java 中的 Ints 類
Ints 類是基本型別 int 的實用程式類。讓我們看看類宣告 −
@GwtCompatible public final class Ints extends Object
示例
讓我們看一個執行連線的某些方法的示例。Ints 類中的 concat() 函式用於連線作為引數傳遞的陣列 −
import com.google.common.primitives.Ints; import java.util.*; class Demo { public static void main(String[] args) { int[] myArr1 = { 100, 150, 230, 300, 400 }; int[] myArr2 = { 450, 550, 700, 800, 1000 }; System.out.println("Array 1 = "); for(int i=0; i < myArr1.length; i++) { System.out.println(myArr1[i]); } System.out.println("Array 2 = "); for(int i=0; i < myArr2.length; i++) { System.out.println(myArr2[i]); } int[] arr = Ints.concat(myArr1, myArr2); System.out.println("Concatenated arrays = "+Arrays.toString(arr)); } }
輸出
Array 1 = 100 150 230 300 400 Array 2 = 450 550 700 800 1000 Concatenated arrays = [100, 150, 230, 300, 400, 450, 550, 700, 800, 1000]
示例
讓我們看另一個示例 −
import java.util.List; import com.google.common.primitives.Ints; public class GuavaTester { public static void main(String args[]) { GuavaTester tester = new GuavaTester(); tester.testInts(); } private void testInts() { int[] intArray = {1,2,3,4,5,6,7,8,9}; //convert array of primitives to array of objects List<Integer> objectArray = Ints.asList(intArray); System.out.println(objectArray.toString()); //convert array of objects to array of primitives intArray = Ints.toArray(objectArray); System.out.print("[ "); for(int i = 0; i < intArray.length ; i++) { System.out.print(intArray[i] + " "); } System.out.println("]"); //check if element is present in the list of primitives or not System.out.println("5 is in list? " + Ints.contains(intArray, 5)); //Returns the minimum System.out.println("Min: " + Ints.min(intArray)); //Returns the maximum System.out.println("Max: " + Ints.max(intArray)); //get the byte array from an integer byte[] byteArray = Ints.toByteArray(20000); for(int i = 0; i < byteArray.length ; i++) { System.out.print(byteArray[i] + " "); } } }
輸出
[1, 2, 3, 4, 5, 6, 7, 8, 9] [ 1 2 3 4 5 6 7 8 9 ] 5 is in list? true Min: 1 Max: 9 0 0 78 32
廣告