java - 将数组列表转为数组

标签 java arrays methods arraylist

这就是我目前所拥有的

try{
          // Open the file that is the first 
          // command line parameter
          FileInputStream fstream = new FileInputStream("Patient.txt");
          // Get the object of DataInputStream
          DataInputStream in = new DataInputStream(fstream);
          BufferedReader br = new BufferedReader(new InputStreamReader(in));
          String strLine;
          //Read File Line By Line
          List<String> lines = new ArrayList<String>();
          while ((strLine = br.readLine()) != null) {

          }
          //Close the input stream
          in.close();
            }catch (Exception e){//Catch exception if any
          System.err.println("Error: " + e.getMessage());
          }
    ArrayList<Patient1> patients=new ArrayList<Patient1>();
    Patient1 p = new Patient1();
    //set value to the patient object
    patients.add(p);
    System.out.println(p);
    // File i/o

这是我的txt文件

001, "John", 17, 100, 65, 110, 110, 110, 109, 111, 114, 113, "Swaying, Nausea"
002, "Sun Min", 18, 101, 70, 113, 113, 110, 119, 111, 114, 113, "None"
003, "Ray Allen", 25, 103, 74, 110, 110, 110, 109, 111, 108, 109, "Difficulty driving"
004, "Michael Jordan", 26, 104, 84, 114, 115, 118, 117, 119, 120, 123, "Loss of        bladder control"
005, "Kobe Bryant", 28, 110, 80, 118, 119, 120, 119, 120, 120, 120, "None"

我拥有所有的方法和资源,我需要做的就是将数组列表转换为数组,这样我就可以做类似的事情

    Patient1 average[] = {p[0], p[1], p[2], p[3], p[4]};
    int totalage = 0;
    double totalweight = 0;
    for (int i=0; i<average.length; i++) {
    totalage = (average[i].getAge() + totalage);
    totalweight = (average[i].getWeight() + totalweight);

最佳答案

toArray 就是你想要的。

例如

ArrayList<String> l = something();
String[] foo = l.toArray(new String[foo.size()]);

ArrayList toArray

编辑

再看一下你的例子之后。您不需要将其转换为数组,只需在循环中调用 arraylist 上的 get 函数并进行计算即可。您可能需要花一些时间查看 javadoc。

关于java - 将数组列表转为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9091102/

相关文章:

c++ - C++中的方法链接?

java - 让 gson 不要在字段名称周围加上引号

java - 将 double 转换为二进制表示?

java - 如何有意义地为 java.lang.Class<T> 定义 hashCode 和 equals?

javascript - 类型错误 : Cannot read properties of undefined (reading 'map' ) NEXTJS

C# 从另一个方法引用一个方法变量

java - 链表 - insert before 方法会导致链表永远持续下去

带有货币符号的 Java String.format

java - 获取用户在线/离线状态

c - 数组 C 的动态内存分配