正在加载图片...
Chapter 11: Collections of Objects 下面的例子演示了如何返回一个 String数组: //: c11: IceCream. java Returning arrays from methods import com. bruceeckel. simpletest. import java.util.*i ublic class IceCream private static Test monitor new Test( private static Random rand new Random( public static final String[] flavors = f "Chocolate","Strawberry","Vanilla Fudge Swirl" "Mint Chip","Mocha Almond Fudge","Rum Raisin Praline Cream"Mud Pie" public static String[] flavorset (int n)( String[] results new String [n] boolean[] picked new boolean[flavors.length]i nt 0;i i++){ int t t = rand. nextInt(flavors. length while (picked[t])i results [i] s[t]; picked[t] true; return results public static void main (String[] args) t System. out. println "flavorset("+ 1+)=") String[] fl = flavorSet(flavors. length)i for (int 3=0;3< fl length 3++) System. out. println("\t"+ fl[jl)i monitor. expect (new object[] 号f1 avorset\(\\d+) \\t(chocolate l Strawberry l +"Vanilla Fudge SwirllMint Chip Mocha Almond # +"Fudge I Rum Raisin l Praline Cream I Mud flavorset()创建了一个名为 results的 String数组。这个数组的 容量是由传给它的参数n所决定的。接下来它从 flavors数组里面随机 选择 flavors(译者注:表示冰激凌的口味),放到 results中,最后返回 results。返回数组跟返回对象没什么两样——都是一个 reference。因 此数组是不是在 flavorset()或是其他什么地方创建的并不重要。只要 第6页共106页 www.wgqqh.com/shhgs/tij.htmlChapter 11: Collections of Objects 第 6 页 共 106 页 www.wgqqh.com/shhgs/tij.html email:shhgs@sohu.com 下面的例子演示了如何返回一个 String 数组: //: c11:IceCream.java // Returning arrays from methods. import com.bruceeckel.simpletest.*; import java.util.*; public class IceCream { private static Test monitor = new Test( ); private static Random rand = new Random( ); public static final String[] flavors = { "Chocolate", "Strawberry", "Vanilla Fudge Swirl", "Mint Chip", "Mocha Almond Fudge", "Rum Raisin", "Praline Cream", "Mud Pie" }; public static String[] flavorSet(int n) { String[] results = new String[n]; boolean[] picked = new boolean[flavors.length]; for(int i = 0; i < n; i++) { int t; do t = rand.nextInt(flavors.length); while(picked[t]); results[i] = flavors[t]; picked[t] = true; } return results; } public static void main(String[] args) { for(int i = 0; i < 20; i++) { System.out.println( "flavorSet(" + i + ") = "); String[] fl = flavorSet(flavors.length); for(int j = 0; j < fl.length; j++) System.out.println("\t" + fl[j]); monitor.expect(new Object[] { "%% flavorSet\\(\\d+\\) = ", new TestExpression("%% \\t(Chocolate|Strawberry|" + "Vanilla Fudge Swirl|Mint Chip|Mocha Almond " + "Fudge|Rum Raisin|Praline Cream|Mud Pie)", 8) }); } } } ///:~ flavorSet( ) 创建了一个名为 results 的 String 数组。这个数组的 容量是由传给它的参数 n 所决定的。接下来它从 flavors 数组里面随机 选择 flavors(译者注:表示冰激凌的口味),放到 results 中,最后返回 results。返回数组跟返回对象没什么两样——都是一个 reference。因 此数组是不是在 flavorSet( )或是其他什么地方创建的并不重要。只要
<<向上翻页向下翻页>>
©2008-现在 cucdc.com 高等教育资讯网 版权所有