Java中的Ints类
Ints类是原始类型int的实用程序类。让我们看看类声明-
@GwtCompatible public final class Ints extends Object
示例
让我们看一个执行串联方法的示例。concat()
Ints类中的函数用于连接作为参数传递的数组-
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}; //将原语数组转换为对象数组 List<Integer> objectArray = Ints.asList(intArray); System.out.println(objectArray.toString()); //将对象数组转换为基元数组 intArray = Ints.toArray(objectArray); System.out.print("[ "); for(int i = 0; i < intArray.length ; i++) { System.out.print(intArray[i] + " "); } System.out.println("]"); //检查元素是否存在于基元列表中 System.out.println("5 is in list? " + Ints.contains(intArray, 5)); //返回最小值 System.out.println("Min: " + Ints.min(intArray)); //返回最大值 System.out.println("Max: " + Ints.max(intArray)); //从整数获取字节数组 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