簡體   English   中英

如何將ArrayList類型的類元素傳遞給方法

[英]How to pass a class-element of an ArrayList type on to a method

如何將ArrayList類型的元素傳遞給方法? 我的幼稚嘗試遵循以下幾行。

public double example( ArrayList<CMyType> list, String type ){

    double out = list.get(0).type // type should be a placeholder for one of the variables which I defined in CMyType
    return out;

}

public class CMyType {
    public double var1;
    public double var2;
}

您要在此處執行的操作:

double out = list.get(0).type // type should be a placeholder for one of 

如果不使用反射,則無法實現,如下所示:

public double example( ArrayList<CMyType> list, String type ) {
  CMyClass obj = list.get(0);
  Field field = obj.getClass().getDeclaredField(type);
  Object objOut = field.get(obj);
  // you could check for null just in case here
  double out = (Double) objOut;
  return out;
}

您還可以考慮將CMyType類修改為如下形式:

class CMyType {
  private double var1;
  private double var2;

  public double get(String type) {
    if ( type.equals("var1") ) {
      return var1;
    } 
    if ( type.equals("var2") ) {
      return var2;
    }

    throw new IllegalArgumentException();
}

然后從您的代碼中調用它,如下所示:

public double example( ArrayList<CMyType> list, String type ) {
  CMyClass myobj = list.get(0);
  return myobj.get(type);
}

更好的解決方案是在CMyType使用Map<String, Double> ,如下所示:

class CMyType {
  private Map<String, Double> vars = new HashMap();

  public CMyType() {
    vars.put("var1", 0.0);
    vars.put("var2", 0.0);
  }

  public double get(String type) {
    Double res = vars.get(type);
    if ( res == null ) throw new IllegalArgumentException();
    return res;
}

為什么不只是

public double example( ArrayList<CMyType> list, String type ){
    double out = list.get(0).type // type should be a placeholder for one of the variables which I defined in CMyType
    return out;
}

public class CMyType {
    public double var1;
    public double var2;
}

public invocationTest() {
   ArrayList<CMyType> arrayList = new ArrayList<CMyType>(); //or populate it somehow
   return myExample(arrayList.get(0));
}

public double myExample( CMyType member, String type ){
    double out = member.type;
    return out;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM