[英]What is the most effective method to input an array in Java?
I need to read an array stored in a single line in a text file. 我需要读取存储在文本文件中一行中的数组。 What am doing till now is this: 到现在为止正在做什么:
BufferedReader in = /*hook it to the file input stream via an InputStreamReader */
String[] input = in.readLine().split(" ");
for (int i = 0; i < input.length; i++)
array[i] = Integer.parseInt(input[i]);
Here, am using the String array unnecessarily. 在这里,不必要地使用String数组。 How can I remove this redundant step? 如何删除这个多余的步骤?
If you can use the InputStream
and the Scanner
class, you can do something like: 如果可以使用InputStream
和Scanner
类,则可以执行以下操作:
Scanner scanner = new Scanner(inputStream);
List<Integer> list = new ArrayList<Integer>();
while(scanner.hasNext()) {
list.add(scanner.nextInt());
}
BufferedReader in = /*hook it to the file input stream via an InputStreamReader */
String input = in.readLine();
StringBuilder sb = new StringBuilder();
List<Integer> list = new LinkedList<>(); //yours array equivalent
for (int i = 0; i < input.length; i++) {
char ch = input.charAt(i);
if (ch == ' ') {
list.add(Integer.parseInt(sb.toString()));
sb.clear();
} else {
sb.append(ch);
}
}
This way you don't need to create the redundant array. 这样,您无需创建冗余阵列。 I think it's very similar to what split() method does, but it doesn't require to handle regular expressions so the performance should be much better in this case. 我认为这与split()方法非常相似,但是它不需要处理正则表达式,因此这种情况下的性能应该会更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.