Welcome to “Algorithms and the Beauty of Programming” ↑ pay attention to us!
This article was first published on the wechat official account “Beauty of Algorithms and Programming”. Welcome to follow and learn more about this series of blogs in time.
I wrote a very simple MyList as required. What are the problems with this MyList?
Problem description
It’s important to know that the needs of your users will change over time, and that your code will be able to adapt to those changes as they happen.
What if the user’s needs now change and you write a List that can add integer data instead of strings?
I’ll just replace String with Integer, as follows:
This does satisfy the user’s new needs, but it requires rewriting the code, recompiling it, and what if the user’s needs change again and you add a Double? Do you have to change the code again?
Obviously this approach is not reliable, so is there a solution to this situation?
The solution
A new technology to meet the changing needs of these types is Java generics.
We can make the type of element that the user wants to add as a parameter, and the type of element that the user wants to add can be specified by the user. This technique is called generics.
Use generics, because we don’t know what users to add element types, so at the bottom of the array, we can’t use String [] of this type, cannot specify specific array types, and should use a way to save any type of data array, array to save any type of data?
The answer to this question is Object[], because Obejct is the parent of all classes.
This is the code we’ve finally modified, and now we’ll write test code to test it.
With the generics mechanism, we can switch between different element types. No matter what type of element the user wants to add, there is no need to modify the code, which is well adapted to the needs of the user.
conclusion
In view of the problem that the MyList designed last time could not adapt to the change of element type, this paper proposed the use of generic mechanism to solve it, and further improved the code to meet the needs of adding any element type.
Keep thinking, what are the problems with the improved code? Feel free to leave a comment below.