0

How would I pass an element of an ArrayList type on to a method? My naive attempt goes along the lines below.

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;
}
Christian
  • 667
  • 6
  • 17

2 Answers2

1

The thing you are trying to do here:

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

is not possible without the use of reflection, like this:

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;
}

You can also consider on modifying your CMyType class to look like this:

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();
}

and then call it from your code like this:

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

Even better solution would be to use Map<String, Double> in CMyType like this:

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;
}
stjepano
  • 917
  • 6
  • 14
0

Why not just

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;
}
Shark
  • 5,787
  • 3
  • 21
  • 46