0

Following is the workflow:

Class A{

    B obj_b = new B;

    String x= "abc";
    String y= "def";

    public void method_a(){
        obj_b.method_b(x,y);
    }  
}

Class B{

    C obj_c = new C;
    public String method_b(String Fname, String Lname){

        ArrayList<String> names = new ArrayList<String>();
        names.add(Fname);
        names.add(Lname);

        String qwerty=("Hello"+ obj_c.method_c(names));

    }
}

Class C{

    public String method_c(ArrayList<String> allElements){
        String xyz = MessageFormat.format(allElements.get(0),allElements.get(1));
        return xyz;
    }
}

What I want to do is:

  1. In Class B, to add all the arguments directly to the ArrayList(i.e. Fname and Lname to names array list). Number of arguments may vary.There might be some other method calling method_b() with 3 or 4 arguments, that is why I am using ArrayList.
  2. Then in Class C, putting each element of the array list(i.e. names) in the method,message(),with comma separated.

Please suggest if any better approach can be taken.

8
  • al.add(Fname); -- what is al? Please post code that can be compiled, this is not valid Java code as al is not declared anywhere. Commented Dec 18, 2017 at 19:52
  • @JimGarrison-Sorry, I have edited the code now. Commented Dec 18, 2017 at 20:01
  • Your method_c is ignoring all but the first 2 elements in the ArrayList. Commented Dec 18, 2017 at 20:01
  • @DM-Yes! this is what I want to know. Right now I know that I have two arguments so I hard coded it. But what if there are many. How to do that?How to put all the elements separated by a comma. Commented Dec 18, 2017 at 20:05
  • @isaace I have edited the code. My bad Commented Dec 18, 2017 at 20:13

1 Answer 1

1

I think you need something like this:

class B {
    C obj_c = new C();

    public void method_b(String... args) {
        List<String> names = Arrays.asList(args);
        String qwerty = "Hello " + obj_c.method_c(names);
    }
}

That way, you can send unlimited args to method_b.

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.