private void addEmUp(int... nums) {
int sum = 0;
for (int each: nums)
sum += each;
out.println("");
out.println("Summing Array: " + Arrays.toString(nums));
out.printf("Sum = %d%n", sum);
}
private void useAddEmUp() {
addEmUp();
addEmUp(10);
addEmUp(10, 20);
addEmUp(10, 20, 30);
addEmUp(10, 20, 30, 40);
}
public void add(String newFirstName) {
this.firstNames.add(newFirstName);
}
public void add(String... names) {
//varargs -- variable number of arguments
//names is a String[] array
for (String newFirstName: names)
add(newFirstName);
}
private void demo_notUsingVarargs() {
Family fam = new Family();
fam.add("Kofi");
fam.add("Sally");
fam.add("Siddhartha");
fam.add("Bao");
out.println("Without varargs -- " + fam.toString());
}
private void demo_usingVarargs() {
Family fam = new Family();
fam.add("Kofi", "Sally", "Siddhartha", "Bao");
out.println("With varargs -- " + fam.toString());
}
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Family { public List<String> firstNames; public Family() { super(); this.firstNames = new ArrayList<>(); } public void add(String newFirstName) { this.firstNames.add(newFirstName); } public void add(String... names) { //varargs -- variable number of arguments //names is a String[] array for (String newFirstName: names) add(newFirstName); } public String toString() { return "Family: " + Arrays.toString(this.firstNames.toArray()); } }
import static java.lang.System.out; import java.util.Arrays; public class FamilyDemo { public static void main(String[] args) { out.println(""); FamilyDemo demo = new FamilyDemo(); demo.demo_notUsingVarargs(); demo.demo_usingVarargs(); demo.useAddEmUp(); out.println(""); } private void demo_notUsingVarargs() { Family fam = new Family(); fam.add("Kofi"); fam.add("Sally"); fam.add("Siddhartha"); fam.add("Bao"); out.println("Without varargs -- " + fam.toString()); } private void demo_usingVarargs() { Family fam = new Family(); fam.add("Kofi", "Sally", "Siddhartha", "Bao"); out.println("With varargs -- " + fam.toString()); } private void addEmUp(int... nums) { int sum = 0; for (int each: nums) sum += each; out.println(""); out.println("Summing Array: " + Arrays.toString(nums)); out.printf("Sum = %d%n", sum); } private void useAddEmUp() { addEmUp(); addEmUp(10); addEmUp(10, 20); addEmUp(10, 20, 30); addEmUp(10, 20, 30, 40); } }
@SafeVarargs public Tuple(T... newArray) { //...