Home >Java >javaTutorial >Item Get to know and use libraries
Avoid reinventing the wheel:
When facing common problems, it's tempting to write ad hoc solutions, but libraries offer optimized, tested, and reliable implementations.
Example:
// Gerando um número aleatório (solução ad hoc com problemas) static int random(int n) { return Math.abs(rnd.nextInt()) % n; }
Problems with this approach include:
Random rnd = new Random(); int randomNum = rnd.nextInt(n); // Correto e seguro
Use ThreadLocalRandom:
As of Java 7, ThreadLocalRandom is faster and should be preferred over Random in many cases:
int randomNum = ThreadLocalRandom.current().nextInt(n); // 3.6x mais rápido que Random
Advantages of using standard libraries:
// Exemplo de uso do método transferTo para transferir dados de um InputStream para um OutputStream try (InputStream in = url.openStream(); OutputStream out = new FileOutputStream("output.txt")) { in.transferTo(out); // Simples e eficiente }
Common libraries to know:
Familiarize-se com as bibliotecas centrais, como java.lang, java.util, java.io, e seus subpacotes. Conheça o framework de coleções e a biblioteca de streams, além dos utilitários de concorrência em java.util.concurrent.
When not to use libraries:
Conclusion:
The above is the detailed content of Item Get to know and use libraries. For more information, please follow other related articles on the PHP Chinese website!