【问题标题】:Convert a string array to an object array将字符串数组转换为对象数组
【发布时间】:2021-05-09 06:51:42
【问题描述】:

我有一个 String 数组,其中包含 10 个客户的 nameagegender。我试图将其转换为Customer 数组。我试图将String 数组的每个元素复制到Customer 数组中,但它不兼容。 如何将String数组中的元素插入Customer数组?

//String[] customerData is given but too long to copy
Customer[] custs = new Customer[numberOfCustomer];
for (int x = 0; x < customerData.length; x++) {
    custs[x] = customerData[x];
}

【问题讨论】:

    标签: java arrays string object


    【解决方案1】:

    在循环内创建一个临时客户对象并用数据填充它。然后将 custs[x] 分配给临时对象。

    【讨论】:

      【解决方案2】:

      假设 Customer 类有一个 all-args 构造函数 Customer(String name, int age, String gender) 并且输入数组包含所有字段,例如:

      String[] data = {
          "Name1", "25", "Male",
          "Name2", "33", "Female",
      // ...
      };
      

      客户数组可以这样创建和填充:

      Customer[] customers = new Customer[data.length / 3];
      for (int i = 0, j = 0; i < customers.length && j < data.length; i++, j += 3) {
          customers[i] = new Customer(data[j], Integer.parseInt(data[j + 1]), data[j + 2]);
      }
      

      【讨论】:

        【解决方案3】:

        如果您在Customer 类中有一个二维字符串数组和一个全参数构造函数,那么您可以将一个字符串数组转换为一个对象数组 像这样:

        static class Customer {
            String name, age, gender;
        
            public Customer(String name, String age, String gender) {
                this.name = name;
                this.age = age;
                this.gender = gender;
            }
        
            @Override
            public String toString() {
                return name + " " + age + " " + gender;
            }
        }
        
        public static void main(String[] args) {
            String[][] arrStr = {
                    {"John1", "22", "Male"},
                    {"John2", "21", "Male"},
                    {"John3", "23", "Male"},
                    {"John4", "24", "Male"},
                    {"John5", "20", "Male"}};
        
            Customer[] customers = Arrays.stream(arrStr)
                    // convert an array of strings to an array of objects
                    .map(arr -> new Customer(arr[0], arr[1], arr[2]))
                    .toArray(Customer[]::new);
        
            // output
            Arrays.stream(customers).forEach(System.out::println);
        }
        

        输出:

        John1 22 Male
        John2 21 Male
        John3 23 Male
        John4 24 Male
        John5 20 Male
        

        【讨论】:

          【解决方案4】:

          你有 json 字符串,使用 objectMapper 将 json 字符串转换为对象。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2019-03-14
            • 2018-12-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多