[英]Why do I need to cast a character for an Integer variable but not for an int?
[英]Why do I need to convert from Integer[] to int[]?
我有以下代碼
public static int[] readCSV() {
ArrayList<Integer> entries = new ArrayList<>();
try {
File file = new File("someDataFile.csv");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = "";
String[] row;
while((line = br.readLine()) != null) {
row = line.split(",");
for(String value : row) {
int entry = Integer.parseInt(value);
entries.add(entry);
}
}
br.close();
} catch(IOException ioe) {
ioe.printStackTrace();
}
int[] IDs = entries.toArray();
return IDs;
}
csv 的每個條目都是存儲為字符串的整數。 我收到以下錯誤:“類型不匹配:無法從 Object[] 轉換為 int[]”。 據我了解,這里的“條目”不是Object[]
,而是ArrayList<Integer>
。
我正在使用geeksforgeeks 上給出的示例。 那沒有用,我不確定為什么。
我還檢查了同一問題的先前答案,最佳答案對我有用。 也就是說,我仍然沒有int[]
,我只有Integer[]
。 然后我必須這樣做才能從Integer[]
轉換為int[]
。 我的問題是為什么我必須做所有這些而不是int[] IDs = entries.toArray();
?
如果我做
int[] IDs = new int[entries.size()];
for (int i=0; i<entries.size(); i++) {
IDs[i] = entries.get(i);
}
它工作正常。 為什么這與int[] IDs = entries.toArray()
不同?
有沒有更好的方法在int[]
中獲取 csv 文件的內容?
首先,回答您的問題,因為集合(如ArrayList
)只能包含對象實例。 這意味着您必須使用Integer
包裝類型而不是int
原始類型。 但是,在 Java 8+ 中,有一些簡單的方法可以執行該轉換。 我還強烈建議使用try-with-Resources
而不是手動關閉BufferedReader
。 我還稍微簡化了代碼。 喜歡,
public static int[] readCSV() {
List<Integer> entries = new ArrayList<>();
File file = new File("someDataFile.csv");
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
String[] row = line.split("\\s*,\\s*"); // Consume white space
for (String value : row) {
entries.add(Integer.parseInt(value));
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return entries.stream().mapToInt(Integer::intValue).toArray();
}
List#toArray
總是返回一個Object[]
。 您可以獲得的最接近的是entries.toArray(new Integer[0])
以獲得Integer[]
。
要獲得int[]
,您可以使用 Streams API 或遍歷List
並將其復制到數組中。
Integer[] arr = list.toArray(new Integer[0]);
int[] arr2 = list.stream().mapToInt(i -> i).toArray();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.