简体   繁体   English

用Java输入数组最有效的方法是什么?

[英]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: 如果可以使用InputStreamScanner类,则可以执行以下操作:

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.

相关问题 在用户输入的相关部分和数组之间找到匹配项的最有效方法是什么? - What is the most effective way to find a match between the relevant parts of user input and an array? 重构这个简单方法的最有效方法是什么? - What's the most effective way to refactor this simple method? 在 Jsp 中打印字符串数组的 Arraylist 最有效的方法是什么? - What is the most effective way of printing Arraylist of string array in Jsp? 什么是最有效的按钮单击? - What Are The Most Effective Clicks For The Button? 有效的Java:sureCapacity()方法 - Effective Java: ensureCapacity() method 在有效的Java书中正确声明读取解析方法意味着什么? - What is meant by proper declaration of read resolve method in the Effective Java book? 使用Java处理单词收缩的有效方法是什么? - What is the effective method to handle word contractions using Java? 有效的Java:什么是泛型数组创建警告 - Effective Java: What is exactly generics array creation warning 使用Android NDK将C ++对象传递给Java的最有效方法是什么? - What is the most effective way to pass a C++ Object to Java using Android NDK 使用Java 7在生产应用程序中没有任何泄漏的情况下读取文件的最有效方法是什么 - What is the most effective way to read a file without any leaks in production app using java 7
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM