Tony Wolff Tony Wolff - 3 years ago 173
Java Question

Is there a way in Java to pass multiple parameter pairs to a method?

Pretty new to Java

I would like to be able to use a method in following sort of way;

class PairedData {
String label;
Object val:
}


public void myMethod(String tablename, PairedData ... pD) {
/*
insert a record into a table -tablename with the various fields being
populated according to the information provided by the list of
PairedData objects
*/
}

myMethod("firststring",{"field1",Date1},{"field2",12},{"field3","aString"});


I realise the syntax is not valid but I hope it gives the gist of what I would like to do.

What I am trying to do is to directly pass the data rather than populate the instances of the class and then pass those. Is that possible or am I just trying to break a whole lot of OOPs rules?

Answer Source

No, what you're trying to do really isn't possible. It looks to me like it would be much better to pass instances of your class to the method as opposed to doing something convoluted with arrays like that. Another answer suggested using an Object[] varargs parameter - that's probably the closest you'll get to achieving something like what you show in your example. Another alternative (and I think a better one) would be

public void myMethod(String tablename, String[] labels, Object[] vals) {

You could instantiate your class for each labels[i] and vals[i] (pairing them up) in those arrays. In other words, in your method you could have something like

pD = new PairedData[labels.length];

for (i = 0; i < labels.length; i++)
    pD[i] = new PairedData(labels[i], vals[i]);  // assuming you
                                                 // added this
                                                 // constructor

The method call example that you included would then be converted to

myMethod("firststring", new String[]{"field1", "field2", "field3"}, 
                                             new Object[]{date1, 12, "aString"});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download