【问题标题】:Creating an array list of multiple data types in Java在 Java 中创建多个数据类型的数组列表
【发布时间】:2016-11-13 03:33:13
【问题描述】:

我正在处理的一些文件:http://pastebin.com/WriQcuPs

目前我必须制作人口、纬度和经度字符串,否则我将无法获得所需的输出。我希望它们按顺序是 int、double 和 double。

public class City {
    String countrycode;
    String city;
    String region;
    String population;
    String latitude;
    String longitude;

    public City (String countrycode, String city, String region, String population, String latitude, String longitude) {
        this.countrycode = countrycode;
        this.city = city; 
        this.region = region;
        this.population = population;
        this.latitude = latitude;
        this.longitude = longitude;
    }

    public String toString() {
        return this.city + "," + this.population 
                + "," + this.latitude + ","
                + this.longitude; 
    }
}

我怀疑这与我创建数组列表的方式有关。有没有办法使列表中的某些元素具有不同的类型?我尝试将其更改为 ArrayList<City> 并更改 City 类中的数据类型,但它仍然给了我很多错误。

public class Reader {

    In input = new In("file:world_cities.txt");
    private static City cityInfo;

    public static void main(String[] args) {
        // open file
        In input = new In("world_cities.txt");
        input = new In("world_cities.txt");
        try {
        // write output to file
        FileWriter fw = new FileWriter("cities_out.txt");
        PrintWriter pw = new PrintWriter(fw);

        int line = 0;

        // iterate through all lines in the file
        while (line < 47913) {

            // read line
            String cityLine = input.readLine();

            // create array list
            ArrayList<String> cityList = new ArrayList<String>(Arrays.asList(cityLine.split(",")));

            // add line to array list
            cityList.add(cityLine);

            // increase counter
            line += 1;      

            // create instance
            cityInfo = new City(cityList.get(0), cityList.get(1), cityList.get(2), cityList.get(3), cityList.get(4), cityList.get(5));
            System.out.println(cityInfo);

            // print output to file 
            pw.println(cityInfo); 
        }

        // close file
        pw.close();
        }

        // what is printed when there is an error when saving to file
        catch (Exception e) {
            System.out.println("ERROR!");
        }

        // close the file
        input.close();
    }
}

【问题讨论】:

    标签: java arraylist


    【解决方案1】:

    如果按如下方式声明列表,则可以将任何引用类型的实例放入其中:

        List<Object> list = new ArrayList<>();
    

    但缺点是当你从列表中获取一个元素时,该元素的静态类型将是Object,你需要将它类型转换为你需要的类型。

    另请注意,您不能将intdouble 放入List。原始类型不是引用类型,List API 要求元素是引用类型的实例。您需要使用相应的包装器类型;即IntegerDouble


    查看您的更多代码,我发现了这一点:

    ArrayList<String> cityList = 
        new ArrayList<String>(Arrays.asList(cityLine.split(",")));
    

    如果您将列表更改为List&lt;Object&gt;,其中对象为IntegerDouble,您将无法这样构建您的列表。

    事实上,我越看这个,我越觉得你根本不需要列表。你应该这样做:

        // read line
        String cityLine = input.readLine();
    
        String[] parts = cityLine.split(",");
        // increase counter
        line += 1;      
    
        // create instance
        cityInfo = new City(parts[0], parts[1], parts[2], 
                            Integer.parseInt(parts[3]),
                            Double.parseDouble(parts[4]),
                            Double.parseDouble(parts[5]));
    

    注意:那里根本没有List!!

    【讨论】:

    • 太棒了!效果很好。非常感谢!
    【解决方案2】:

    您可以在将字符串值传递到新的City 对象之前对其进行解析。然后,您可以将 City 中的构造函数和变量更改为 int、double 和 double。

    int pop = Integer.parseInt(cityList.get(3));
    double latitude = Double.parseDouble(cityList.get(4));
    double longitude = Double.parseDouble(cityList.get(5));
    cityInfo = new City(cityList.get(0), cityList.get(1), cityList.get(2), pop, latitude, longitude);
    

    【讨论】:

      【解决方案3】:

      通过查看City 类,您已经定义了成员属于不同的原始数据类型。当您读取文件以创建城市时,您需要使用在构造函数中定义的数据类型传递构造函数参数。

      修改你的City类如下:

      public class City {
          String countrycode;
          String city;
          String region;
          int population;
          double latitude;
          double longitude;
      ...
      

      尝试以下方法:

      cityInfo = new City(cityList.get(0), cityList.get(1), cityList.get(2), Integer.parseInt(cityList.get(3)), Double.parseDouble(cityList.get(4)), Double.parseDouble(cityList.get(5)));
      

      这会将字符串转换为 City 类所需的 int 和 double。

      【讨论】:

        【解决方案4】:

        我相信不,但你可以做到这一点

        public class City {
        String countrycode;
        String city;
        String region;
        String population;
        double latitude;
        double longitude;
        
        public City (String countrycode, String city, String region, String population, double latitude, double longitude) {
            this.countrycode = countrycode;
            this.city = city; 
            this.region = region;
            this.population = population;
            this.latitude = latitude;
            this.longitude = longitude;
        }
        
        public String toString() {
            return this.city + "," + this.population 
                    + "," + this.latitude + ","
                    + this.longitude; 
        }
        }
        
        public class Reader {
        
        In input = new In("file:world_cities.txt");
        private static City cityInfo;
        
        public static void main(String[] args) {
            // open file
            In input = new In("world_cities.txt");
            input = new In("world_cities.txt");
            try {
            // write output to file
            FileWriter fw = new FileWriter("cities_out.txt");
            PrintWriter pw = new PrintWriter(fw);
        
            int line = 0;
        
            // iterate through all lines in the file
            while (line < 47913) {
        
                // read line
                String cityLine = input.readLine();
        
                // create array list
                ArrayList<String> cityList = new ArrayList<String>(Arrays.asList(cityLine.split(",")));
        
                // add line to array list
                cityList.add(cityLine);
        
                // increase counter
                line += 1;      
        
                // create instance
                cityInfo = new City(cityList.get(0), cityList.get(1), cityList.get(2), cityList.get(3), Doule.parseDouble(cityList.get(4)), Doule.parseDouble(cityList.get(5)));
                System.out.println(cityInfo);
        
                // print output to file 
                pw.println(cityInfo); 
            }
        
            // close file
            pw.close();
            }
        
            // what is printed when there is an error when saving to file
            catch (Exception e) {
                System.out.println("ERROR!");
            }
        
            // close the file
            input.close();
        }
        }
        

        【讨论】:

          【解决方案5】:

          你可以这样做:

          阅读器类

          import java.io.FileWriter;
          import java.io.PrintWriter;
          import java.util.ArrayList;
          import java.util.Arrays;
          
          public class Reader {
          
              In input = new In("file:world_cities.txt");
              private static City cityInfo;
          
              public static void main(String[] args) {
                  // open file
          //        In input = new In("world_cities.txt");
          //        input = new In("world_cities.txt");
                  try {
                  // write output to file
                  FileWriter fw = new FileWriter("cities_out.txt");
                  PrintWriter pw = new PrintWriter(fw);
          
                  int line = 0;
          
                  // iterate through all lines in the file
                  while (line < 47913) {
          
                      // read line
                      String cityLine = input.readLine();
          
                      // create array list
                      ArrayList<String> cityList = new ArrayList<String>(Arrays.asList(cityLine.split(",")));
          
                      // add line to array list
                      cityList.add(cityLine);
          
                      // increase counter
                      line += 1;      
          
                      // create instance
                      cityInfo = new City(cityList.get(0), cityList.get(1), cityList.get(2), Integer.parseInt(cityList.get(3)), Double.parseDouble(cityList.get(4)), Double.parseDouble(cityList.get(5)));
                      System.out.println(cityInfo);
          
                      // print output to file 
                      pw.println(cityInfo); 
                  }
          
                  // close file
                  pw.close();
                  }
          
                  // what is printed when there is an error when saving to file
                  catch (Exception e) {
                      System.out.println("ERROR!");
                  }
          
                  // close the file
                  input.close();
              }
          }
          

          城市等级

          public class City {
              String countrycode;
              String city;
              String region;
              int population;
              double latitude;
              double longitude;
          
              public City (String countrycode, String city, String region, int population, double latitude, double longitude) {
                  this.countrycode = countrycode;
                  this.city = city; 
                  this.region = region;
                  this.population = population;
                  this.latitude = latitude;
                  this.longitude = longitude;
              }
          
              public String toString() {
                  return this.city + "," + this.population 
                          + "," + this.latitude + ","
                          + this.longitude; 
              }
          }
          

          【讨论】:

            【解决方案6】:

            有没有办法让列表中的一些元素 不同的类型?

            List 可以包含不同类型的元素,但如果您使用 String.split() 填充它则不行——因为这会返回 String[]

            例如,您可以使用 Java 原始类型包装器上的 valueOf 方法将从 String.split() 返回的字符串转换为所需的类型...

            Integer population = Integer.valueOf("1234567");  // Returns 1234567 as an Integer, which can autobox to an int if you prefer
            

            【讨论】:

              【解决方案7】:

              就像斯蒂芬建议的那样,您可以使用List&lt;Object&gt;,除此之外,您可以将字符串传递给 City,但让 City 自己处理数据类型。

              public class City {
                  String countrycode;
                  String city;
                  String region;
                  int population;
                  double latitude;
                  double longitude;
              
                  public City (String countrycode, String city, String region, String population, String latitude, String longitude) {
                      this.countrycode = countrycode;
                      this.city = city; 
                      this.region = region;
                      try{
                          this.population = Integer.parseInt(population);
                          this.latitude = Double.parseDouble(latitude);
                          this.longitude = Double.parseDouble(longitude);
                      }catch(Exception e){
                          e.printStacktrace();
                      }
              
                  }
              
                  public String toString() {
                      return this.city + "," + this.population 
                              + "," + this.latitude + ","
                              + this.longitude; 
                  }
              }
              

              顺便说一句,你已经发起了两次In

              In input = new In("world_cities.txt");
              input = new In("world_cities.txt");
              

              修改为

              In input = new In("world_cities.txt");
              

              【讨论】:

              • 哎呀!好收获!
              猜你喜欢
              • 2015-05-14
              • 2021-11-18
              • 2011-07-22
              • 1970-01-01
              • 2014-04-13
              • 2017-12-19
              • 1970-01-01
              • 1970-01-01
              • 2018-11-08
              相关资源
              最近更新 更多