简体   繁体   English

有没有简单的方法可以返回整数值或双精度值?

[英]Is there a simple way to return either a integer value and or double value?

I'm recreating something similar to pandas dataframe in java to read csv files and manipulate data. 我正在重新创建类似于Java中的pandas数据框的内容,以读取csv文件并处理数据。 I have everything coded as generic to handle any type of column in a csv file as well as auto declaration to wrapper classes such as Integer and Double if it is a number. 我已将所有代码编码为通用代码,以处理csv文件中的任何类型的列,并自动声明包装类(例如Integer和Double)(如果是数字)。 The problem is that now I'm writing functions that will only concern Numeric columns, but I still need to do a decent amount of casting to get the actual values which I would like to find a more elegant solution to. 问题在于,现在我正在编写仅涉及数字列的函数,但是我仍然需要进行大量的转换才能获得实际值,而我希望找到一种更优雅的解决方案。

I have tried casting within the methods and it works but I'm looking for a way to just return the numeric value if it is a number within the column class to avoid doing this for future functions: 我已经尝试在方法中进行强制转换并且可以正常工作,但是我正在寻找一种方法来返回数字值(如果它是列类中的数字),以避免将来为函数执行此操作:

  //the basic structure
  public class Column<T> {
  public String type; //column type
  public String name; //column name
  public ArrayList<T> values; //array of values
...
  public T getValue(int index) {
      return values.get(index);
  }
}


//in another file is the problem
public static double variance(Column c) {
    double mean = mean(c);
    double var = 0;
    for(int i = 0;i < c.getLength();i++) {
                            // here is the problem
        var = Math.pow((((Number) c.getValue(i)).doubleValue()-mean),2);
    }
    return var/c.getLength();
  }

If you have the freedom to modify your Column class or make another, more specific subclass, instead of doing a cast outside the object, you could add methods to return a double internally if it's a double, an int if it's an int, etc, since in your example you know that Column is a Column<Number> . 如果您可以修改Column类或创建另一个更具体的子类,而不必在对象外部进行强制转换,则可以添加方法以在内部返回double值(如果是double值),int值(如果是int值)等等。因为在您的示例中您知道ColumnColumn<Number> For example: 例如:

public class DoubleColumn extends Column<Number> {
    @Override
    public Double getValue(int index) {
        return super.getValue(index).doubleValue();
    }
}

Then you can modify your variance method accordingly to take a DoubleColumn instead of a Column . 然后,您可以相应地修改方差方法以采用DoubleColumn而不是Column

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM