In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "what are the common mistakes in Java". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1. Ignore access modifier
Although a little baffling, candidates do often forget the scope of the protected access modifier in Java. Maybe it's because they are so anxious and nervous during the interview that they can usually only answer one of them:
Protected fields, methods, and constructors can be accessed from subclasses.
Protected fields, methods, and constructors can be accessed from the same package.
In addition, the scope of the package can help many developers write their own tests: protected methods can be accessed from the test path. So forgetting this attribute is tantamount to showing in the interview that you have never written a test!
two。 String concatenation
If you use a large number of strings or large strings, you may waste a lot of memory during the connection process.
The above example is to create some StringBuilder and String objects: 10.000.000 StringBuilder and 10.000.001 String, to be exact.
Explanation:
Take a step back and see what happened.
When you use the + operator for string concatenation, an intermediate object is created that stores the result of the connection and assigns the result to the target object.
In the example above, a total of three objects are created: two for text and one for concatenation, a copy of the first string result plus the second string "world!". Because String is immutable, this string concatenation is possible.
But the compiler is smart enough to convert the code to the following (Java9+ is not applicable because it uses StringContactFacotry, but the results are very similar):
This optimization removes the intermediate connection object, and memory is occupied by two string text and one StringBuilder. Overall, the number of string objects has dropped from O (n ²) to O (n).
Going back to the first example, the compiler optimizes the code as follows:
The compiler just optimizes internal connections, but this creates a lot of StringBuilder and String objects! The correct way to connect a string is as follows, only a StringBuilder and a String are needed.
3. Equals () is not used
If you are using the = = (comparison operator) instead of calling the equals () function, you need to change this habit, and the results can be surprising.
Explanation:
Do not use = = when you want to compare two String and any other object. = = compare only the object references (memory address comparison) of the two operands, not the content.
In the above example, the string cannot activate the string resident mechanism: its memory address is different from x.
4. Return to null
The author has found this method many times:
The problem with returning null is to force the caller to check for null results; in this case, if there are no items, the caller will return an empty list.
Developers always want to return an exception or special object (such as an empty list), otherwise the application that uses the code will be affected by NullPointerException.
5. The password is a string
Storing user-supplied passwords in string objects is a security issue, and strings are vulnerable to memory attacks.
You should use char [], just as JPasswordField and Password4j are doing. But if you're talking about Web applications, most Web containers pass plain text passwords in HttpServletRequest objects as String, so there's little developers can do about it.
Explanation:
Strings are cached by the Java virtual machine (JVM) (resident) and stored in the PermGen space (before Java8) or in the heap space. In both cases, the cache value is deleted only after garbage collection occurs: this means that there is no way to know when a particular value will be deleted from the string pool, because the behavior of the garbage collector is uncertain.
Another problem is that String are immutable, so they cannot be cleared. However, char [] is mutable and can be deleted after processing (for example, replacing each element with 0). With this simple technique, attackers can only find arrays with all zeros in memory instead of plain text passwords.
6. Transfer null
Passing null means taking it for granted that the calling code can manage the null. If not, the application will definitely throw a NullPointerException.
In addition, explicitly passing null can make the code more and more confusing. Here is a typical example:
When init () is called, there is no User object available. So, if you don't have a User, why call a function that operates on User? If you need the logic in grantAccessToUser (), you should extract and use it from other functions instead of passing null.
7. Heavy methods
The following example may result in loss of system performance:
Pattern.compile () is a resource-intensive function that should not be called every time a string is checked to see if it matches the same pattern.
Explanation:
Pattern.compile () precompiles the schema to use a faster memory representation. Compared with a single match, this operation requires a lot of computing power.
A classic way to increase performance is to cache the Pattern object in a static field, as follows:
You should use this solution every time you use a stateless object that takes up a lot of resources.
8. Deal with collections during iteration
This code will throw a ConcurrentModificationException.
Explanation:
When you delete an item from the list during an iteration, the list iterator runs poorly, such as skipping elements, repeating elements, the end of an indexed array, and so on. This is why many collections are more likely to throw oncurrentModificationException.
Use the underlying array iterator:
9. Use "return code" instead of throwing an exception
In a sense, developers think that exceptions are ominous, so they tend to write functions that return strange values, such as-1 or "C_ERR".
This is a typical case where it is worth creating a custom Exception. The example can be rewritten as follows:
As you can see, the readability and maintainability of the code are greatly improved. The caller only needs to read the contents of the DeviceStartException and does not have to process each return code.
10. Use StringBuffer
Due to the synchronization nature of StringBuffer, this example produces a large memory footprint. In more complex environments, readers may mistakenly assume that some unnecessary synchronization is necessary.
If your project includes StringBuffer, it may be because some legacy API (that is, before Java5) needs it, and rarely because the code attempts to append String in a concurrent environment. Use StringBuilder instead: introduced in Java5, all of its operations are out of sync.
These are only some of the mistakes I saw in interviews and active projects, and I haven't mentioned the pitfalls, design patterns, overdesign, memory leaks and other defects of object-oriented programming (OOP).
If you have these problems, it's time to change your coding style. This is not difficult, avoiding these traps can enhance the developer's experience and make people proactively prepare for the next interview.
Use more static code analyzers like SonarQube, which can point out actual errors and highlight potential errors.
This is the end of the content of "what are the common mistakes in Java"? thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.