Guava庫中Floats類的toArray()方法用於將作為參數傳遞給此方法的float值轉換為Float數組。這些浮點值作為Collection傳遞給此方法。此方法返回一個Float數組。
用法:
public static float[] toArray(Collection<? extends Number> collection)
參數:此方法接受強製性參數集合,該參數集合是要轉換為Float數組的float值的集合。
返回值:此方法以相同的順序返回包含與集合相同的值的float數組。
異常:如果傳遞的集合或其任何元素為null,則此方法將引發NullPointerException。
以下示例程序旨在說明toArray()方法的使用:
範例1:
// Java code to show implementation of
// Guava's Floats.toArray() method
import com.google.common.primitives.Floats;
import java.util.Arrays;
import java.util.List;
class GFG {
// Driver's code
public static void main(String[] args)
{
// Creating a List of Floats
List<Float> myList
= Arrays.asList(1.2f, 2.3f, 3.4f, 4.5f, 5.6f);
// Using Floats.toArray() method to convert
// a List or Set of Float to an array of Float
float[] arr = Floats.toArray(myList);
// Displaying an array containing each
// value of collection,
// converted to a float value
System.out.println(Arrays.toString(arr));
}
}
輸出:
[1.2, 2.3, 3.4, 4.5, 5.6]
範例2:
// Java code to show implementation of
// Guava's Floats.toArray() method
import com.google.common.primitives.Floats;
import java.util.Arrays;
import java.util.List;
class GFG {
// Driver's code
public static void main(String[] args)
{
try {
// Creating a List of Floats
List<Float> myList
= Arrays.asList(1.2f, 2.3f, 3.4f, null);
// Using Floats.toArray() method
// to convert a List or Set of Float
// to an array of Float.
// This should raise "NullPointerException"
// as the collection contains "null"
// as an element
float[] arr = Floats.toArray(myList);
// Displaying an array containing each
// value of collection,
// converted to a float value
System.out.println(Arrays
.toString(arr));
}
catch (Exception e) {
System.out.println(e);
}
}
}
輸出:
java.lang.NullPointerException
相關用法
- Java Guava Doubles.min()用法及代碼示例
- Java Guava Doubles.contains()用法及代碼示例
- Java Guava Floats.contains()用法及代碼示例
- Java Guava Bytes.contains()用法及代碼示例
- Java Guava Longs.contains()用法及代碼示例
- Java Guava Shorts.min()用法及代碼示例
- Java Guava Longs.min()用法及代碼示例
- Java Guava Chars.min()用法及代碼示例
- Java Guava Floats.min()用法及代碼示例
- Java Guava Longs.max()用法及代碼示例
- Java Guava Doubles.max()用法及代碼示例
- Java Guava Chars.max()用法及代碼示例
- Java Guava Floats.max()用法及代碼示例
- Java Guava Booleans.contains()用法及代碼示例
- Java Guava Shorts.contains()用法及代碼示例
注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 Java Guava | Floats.toArray() method with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。