CATEGORII DOCUMENTE |
Asp | Autocad | C | Dot net | Excel | Fox pro | Html | Java |
Linux | Mathcad | Photoshop | Php | Sql | Visual studio | Windows | Xml |
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:
//: IceCream.java
// Returning arrays from methods
public class IceCream ;
static String[] flavorSet(int n)
}
return results;
}
public static void main(String[] args)
}
} ///:~
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 | Termeni si conditii de utilizare |
Vizualizari: 742
Importanta:
Termeni si conditii de utilizare | Contact
© SCRIGROUP 2024 . All rights reserved