0

I have a method to send email whose signature is

sendemail(Vector addr, String subject, String body)

zvector addr contains email address to which the email has to be sent.

If we have multiple, separated email addresses then we add each to Vector and pass it. But now I want to send the email to only 1 address.

So can I pass the String email address directly to the method or need to add single string also to the Vector?

Abhishek kumar
  • 2,586
  • 5
  • 32
  • 38
  • BTW: [Vector is seldom appropiate](http://stackoverflow.com/questions/1386275/why-is-java-vector-class-considered-obsolete-or-deprecated). And Java classes are case sensitive (vector => Vector, string => String) – leonbloy Feb 08 '13 at 18:41
  • sorry while writing here typing error. – Abhishek kumar Feb 08 '13 at 18:42

4 Answers4

2

You will need to create a one-element Vector. Here's a method to create a one-item Vector:

public <T> Vector<T> singletonVector(T item) {
    Vector<T> v = new Vector<T>(1);
    v.add(item);
    return v;
}

If you change your sendemail method to take a java.util.List instead, you could use the Collections.singletonList method to create your one-item List. And since Vector implements List, you won't have to change any existing code that calls sendemail.

sendemail(Collections.singletonList(emailAddress), mySubject, myBody);
Brigham
  • 14,395
  • 3
  • 38
  • 48
2

You definitely need to instantiate a new vector<String> and add the String to it.

Another solution would be to overload the function with a different signature:

sendemail(Vector<String> addr, String subject, String body) {
  ..
}

sendemail(String addr, String subject, String body) {
  Vector<String> vaddr = new Vector<String>();
  vaddr.add(addr);
  sendemail(vaddr, subject, body);
}

So that a new Vector is still instantiated but at least you can use which one signature you prefer.

Jack
  • 131,802
  • 30
  • 241
  • 343
0

You need to add the single string to the vector.

What you can do if you can modify sendemail is to define it as:

public void sendemail(String subject, String body, String ... addr)

and then you don't need to construct a vector, you just pass the addresses.

Luis
  • 1,294
  • 7
  • 9
  • sendemail email is an existing functionality and is used to send email in multiple scenarios. So i dont think i can change the signature. – Abhishek kumar Feb 08 '13 at 18:29
0
sendemail(String...addr, String subject, String body)
{

    //addr.length(): The number of email address
    //addr[0]: 1st email adrdess 
    //addr[1]: 2nd email adrdess 
    .
    .
    .
    //addr[addr.length-1]: last email adrdess 

}

I recommend you write like this:

sendemail(String...addr)
{

    subject=addr[addr.lentgh-2];
    body=addr[addr.lentgh-1];
    addr[0]..addr[addr.length-3]: email addresses.

}
Machavity
  • 30,841
  • 27
  • 92
  • 100
Malus Jan
  • 1,860
  • 2
  • 22
  • 26