|Access||Adobe photoshop||Algoritmi||Autocad||Baze de date||C||C sharp|
|Calculatoare||Corel draw||Dot net||Excel||Fox pro||Frontpage||Hardware|
|Php||Power point||Retele calculatoare||Sql||Tutorials||Webdesign||Windows|
|Asp||Autocad||C||Dot net||Excel||Fox pro||Html||Java|
Suppose youíre writing a method and you donít just want to return 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 easily leads to memory leaks.
Java takes a similar approach, but you just ďreturn an array.Ē Actually, of course, youíre returning a handle to an array, but with Java 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.
As an example, consider returning an array of String:
The method flavorSet( ) creates an array of String called results. The size of this array is n, determined by the argument you pass into the method. Then it proceeds to choose flavors randomly from the array flav and place them into results, which it finally returns. Returning an array is just like returning any other object Ė itís a handle. Itís not important that the array was created within flavorSet( ), or that the array was created anyplace else, for that matter. The garbage collector takes care of cleaning up the array when youíre done with it, and the array will persist for as long as you need it.
As an aside, notice that when flavorSet( ) chooses flavors randomly, it ensures that a random choice hasnít been picked before. This is performed in a seemingly infinite while loop that keeps making random choices until it finds one thatís not already in the picks array. (Of course, a String comparison could also have been performed to see if the random choice was already in the results array, but String comparisons are inefficient.) If itís successful it adds the entry and breaks out to go find the next one (i gets incremented). But if t is a number thatís already in picks, then a labeled continue is used to jump back two levels, which forces a new t to be selected. Itís particularly convincing to watch this happen with a debugger.
main( ) prints out 20 full sets of flavors, so you can see that flavorSet( ) chooses the flavors in a random order each time. Itís easiest to see this if you redirect the output into a file. And while youíre looking at the file, remember, youíre not really hungry. (You just want the ice cream, you donít need it.)
Politica de confidentialitate|
Adauga cod HTML in site