Πέμπτη 4 Οκτωβρίου 2007

Java varargs...

Καλώς η κακώς η Java ήδη είναι ένα βήμα πρίν την έκδοση 7 και ακόμα δουλεύουμε πάνω σε 1.4sdk :(

Οι λόγοι κυρίως systemικοί απ' ότι έχω καταλάβει.... Ένα όμορφο πραγματάκι που υπάρχει απο την 5 είναι τα varargs.... Για δείτε λιγο:

The varargs, or variable arguments, feature allows a developer to declare that a method can take a variable number of parameters for a given argument. The vararg must be the last argument in the formal argument list.

You might use varargs to allow adding one to many objects to a collection that you have defined by using a single add method call. Suppose you need a method that writes any number of records to the console. Using varargs, you can make any of the following method calls:

write("line 1");
write("line 2", "line 3");
write("line 4", "line 5", "line 6", "line 7", "line 8", "line 9",
"line 10");

Before 1.5, you would need to define overloaded versions of the write method to accomplish this. This isn't an effective solution if you want to be able to support any number of records being passed in.

The write method introduces a couple new bits of syntax:

public void write(String... records) {
for (String record: records)
System.out.println(record);
}

First, the records argument is defined as type String.... This indicates to the compiler that calling code can pass a variable number of String parameters. For all other intents and purposes, however, String... equates to a String array (String[]).

Δεν υπάρχουν σχόλια: