ITeye博客

Thinking in Java 1: Returning an array

prevention · 2012-10-14 01:38 · Markdown

Page 753

Suppose you're writing a method and you don't want to return just one thing, but a whole bunch of things. Languages like C and C++ make this difficult because you can't just return an array, only a pointer to an array. This introduces problems because it becomes messy to control the lifetime of the array, which leads to memory leaks.

In Java, you just return the array. You never worry about responsibility for that array -- it will be around as long as you need it, and the garbage collector will clean it up when you're done.

import java.util.Random;


public class Test {
	
	private static Random rand = new Random(47);
	
	static final String[] FLAVORS = {
		"Chocolate", 
		"Strawberry", 
		"Vanilla Fudge Swirl", 
		"Mint Chip",
		"Mocha Almond Fudge",
		"Rum Raisin",
		"Praline Cream",
		"Mud Pie"
	};
	
	private static String[] test(int n) {
		if (n > FLAVORS.length) {
			throw new IllegalArgumentException("Set too big");
		}
		
		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) {
		int yy = 8;
		int kk = 10; // times
		for (int i = 0; i < kk; i++) {
			String[] x = test(yy);
			System.out.print("[");
			for (int j = 0; j < yy; j++) {
				System.out.print(x[j]);
				if (j != yy - 1) System.out.print(",");
			}
			System.out.println("]");
		}	
	}
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。