java - Method with two indeterminate arguments? -



java - Method with two indeterminate arguments? -

i understand how create limitless arguments per java method unlimited arguments

but wondering syntax extend 2 arguments, akin printf?

i want create unlimited string, int pairs.

the goal display string1 : int1, string2: int2 , on. i'm not sure syntax be, allow lone if it's possible.

it's not straight possible here approaches:

if strings unique, can pass info map:

public void method(map<string,integer> pairs) { ... }

you can utilize 2 separate arrays:

public void method(string[] strings, int[] ints) { if (strings.length != ints.length) throw new illegalargumentexception(); ... }

call as:

method(new string[] { "a", "b", "c" }, new int[] { 1, 2, 3 });

use object , sort out later. suffers ugly internals , lack of compile-time type checking has shortest calling syntax:

public void method(object... args) { if (args.length % 2 != 0) throw new illegalargumentexception(); (int = 0; < args.length; += 2) { string s = (string)args[i + 0]; int = (integer)args[i + 1]; ... } }

use builder-style object:

public pairs method() { homecoming new pairs(); } // create names here meaningful method public static class pairs { private static class pair { string s; int i; } private final list<pair> pairs = new arraylist<>(); private pairs() {} public pairs add(string s, int i) { pair p = new pair(); p.s = s; p.i = i; pairs.add(p); homecoming this; } public void run() { (pair p : pairs) { ... method's work here ... } } }

depending on want accomplish might over-complicating it, gives quite pleasant , type-checked syntax caller:

method() .add("a", 1) .add("b", 2) .add("c", 3) .run();

java methods varargs

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -