Posted on 2009-12-20 00:00
啥都寫點(diǎn) 閱讀(288)
評(píng)論(0) 編輯 收藏 所屬分類:
J2SE
在J2SE5.0之前,當(dāng)傳入到方法的參數(shù)個(gè)數(shù)不固定時(shí),經(jīng)常采用數(shù)組的方式傳遞參數(shù)。5.0之后,可以使用可變長(zhǎng)參數(shù)的特性給方法傳遞參數(shù)。

在參數(shù)類型和參數(shù)名之間使用"...",表示該參數(shù)為可變長(zhǎng)的。

通過新的for循環(huán)讀取可變長(zhǎng)參數(shù)中的值


/** *//**
* 可變長(zhǎng)的參數(shù)。
* 有時(shí)候,我們傳入到方法的參數(shù)的個(gè)數(shù)是不固定的,為了解決這個(gè)問題,我們一般采用下面的方法:
* 1. 重載,多重載幾個(gè)方法,盡可能的滿足參數(shù)的個(gè)數(shù)。顯然這不是什么好辦法。
* 2. 將參數(shù)作為一個(gè)數(shù)組傳入。雖然這樣我們只需一個(gè)方法即可,但是,
* 為了傳遞這個(gè)數(shù)組,我們需要先聲明一個(gè)數(shù)組,然后將參數(shù)一個(gè)一個(gè)加到數(shù)組中。
* 現(xiàn)在,我們可以使用可變長(zhǎng)參數(shù)解決這個(gè)問題,
* 也就是使用
將參數(shù)聲明成可變長(zhǎng)參數(shù)。顯然,可變長(zhǎng)參數(shù)必須是最后一個(gè)參數(shù)。
*/

public class VarArgs
{


/** *//**
* 打印消息,消息數(shù)量可以任意多
* @param debug 是否debug模式
* @param msgs 待打印的消息
*/

public static void printMsg(boolean debug, String
msgs)
{

if (debug)
{
// 打印消息的長(zhǎng)度
System.out.println("DEBUG: 待打印消息的個(gè)數(shù)為" + msgs.length);
}

for (String s : msgs)
{
System.out.println(s);
}

if (debug)
{
// 打印消息的長(zhǎng)度
System.out.println("DEBUG: 打印消息結(jié)束");
}
}

/** *//**
* 重載printMsg方法,將第一個(gè)參數(shù)類型該為int
* @param debugMode 是否debug模式
* @param msgs 待打印的消息
*/

public static void printMsg(int debugMode, String
msgs)
{

if (debugMode != 0)
{
// 打印消息的長(zhǎng)度
System.out.println("DEBUG: 待打印消息的個(gè)數(shù)為" + msgs.length);
}

for (String s : msgs)
{
System.out.println(s);
}

if (debugMode != 0)
{
// 打印消息的長(zhǎng)度
System.out.println("DEBUG: 打印消息結(jié)束");
}
}

public static void main(String[] args)
{
// 調(diào)用printMsg(boolean debug, String
msgs)方法
VarArgs.printMsg(true);
VarArgs.printMsg(false, "第一條消息", "這是第二條");
VarArgs.printMsg(true, "第一條", "第二條", "這是第三條");
// 調(diào)用printMsg(int debugMode, String
msgs)方法
VarArgs.printMsg(1, "The first message", "The second message");
}
} --
學(xué)海無涯