Home >Java >javaTutorial >Item Get to know and use libraries

Item Get to know and use libraries

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-04 06:10:30324browse

Item  Conheça e utilize as bibliotecas

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:

  • Repetitive patterns if n is a power of two.
  • Unequal distribution if n is not a power of two.
  • Risk of error with Math.abs(Integer.MIN_VALUE).
  • Better solution: Use Random.nextInt(int) to generate random numbers efficiently and correctly.
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:

  • Expertise: Library methods are created by experts, tested extensively, and improved over time.
  • Time efficiency: You can focus on developing your application instead of writing supporting infrastructure.
  • Improved performance: Standard libraries are continually optimized.
  • Additional features: Over time, libraries gain new features. Example: The transferTo method was added in Java 9 to make it easier to send data from streams.
// 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:

  • In some cases, your needs may be specialized and not met by standard libraries. In these cases, look for third-party libraries like Google's Guava, or write your own implementation if necessary.

Conclusion:

  • Always summarize with a query: When you need a feature, check whether a library already provides what you need before reinventing solutions.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn