Search code examples
javanamevaluecollection

append a Name Value pair to other one


here is the code of the calling method -

NameValuePair[] data = {
        new NameValuePair("first_name", firstName),
        new NameValuePair("last_name", lastName),
        new NameValuePair("email", email),
        new NameValuePair("company", organization),
        new NameValuePair("phone", phone)
    };
    SalesForceFormSubmissionUtil.submitForm(data,CONTACT_FOR_TYPE);

In the called method -

  public static void submitForm(NameValuePair[] givendata, String contactType) {
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod(Constants.SALESFORCE_URL);
    NameValuePair[] data = {
        new NameValuePair("oid", Constants.SALESFORCE_OID),
        new NameValuePair(Constants.SALESFORCE_CAMPAIGN_ID, contactType)
    };
    post.setRequestBody(data);

i want to add both the givendata & data and send it as a post request. Can you guys suggest me how to append both.


Solution

  • If you just want to combine the two arrays you can create a third array (combinedData) with a size of givenData.length + data.length, then you'll have to copy the elements from your source arrays.

    Though, there are plenty of other methods to solve this, as an example; below is an implementation using a ArrayList as a middle-man/helper.

    String[] A1 = {"hello","world"};
    String[] A2 = {"I","am","bored"};
    
    ...
    
    ArrayList<String> temp = new ArrayList<String> (A1.length + A2.length);
    
    temp.addAll (Arrays.asList (A1));
    temp.addAll (Arrays.asList (A2));
    
    String[] A3 = temp.toArray (new String[temp.size ()]);
    
    ...
    
    for (int i=0; i < A3.length; ++i)
      System.out.println (A3[i]);
    

    output

    hello
    world
    I
    am
    bored