While browsing Stack Overflow, I found bears Ears Mountain of questions, such as this one: Why shouldn’t Java primitives be used? The page views are 205K+, this is great! There are many, many programmers who are troubled by this problem. Let’s be honest, I was one of them before this article.
To recap the questioner’s question:
What are Java primitive types? Why not use primitive types? If you can’t use primitive types, what’s a better choice?
If you have been or are struggling with this question, please come with me and let’s go through this question side by side hand in hand and find the best answer. Duang, Duang, Duang!
What are Java primitive types?
To understand what Java primitive types are, take a look at what generics are.
List<String> list = null;
Copy the code
List is a generic type, which is usually called a String list, that is, a list can only contain elements of String type.
A list is a primitive type if we declare it as follows.
List list = null;
Copy the code
From the list declaration, we can see that the original type does not specify an explicit element type for the container, so we can put a String, an Integer, or even any type in the container, as follows.
public class RawType {
public static void main(String[] args) {
List list = new ArrayList();
list.add("Silent King II.");
list.add(18);
list.add(newRawType()); }}Copy the code
Note that the compiler has no warning! This indicates that Java, a strongly typed language, is a bit of a weakly typed shadow.
PS: For Java type terminology, see the following table.
The term | meaning | For example, |
---|---|---|
Parameterized type | Parameterized type | List<String> |
Actual type parameter | Actual type parameter | String |
Generic type | The generic type | List<E> |
Formal type parameter | Formal type parameter | E |
Unbounded wildcard type | Unrestricted wildcard type | List<? > |
Raw type | The original type | List |
Bounded type parameter | Restricted type parameter | <E extends Number> |
Bounded wildcard type | Restrict wildcard types | List<? extends Number> |
02. Why not use primitive types?
You may have a question, primitive type is very cool to use ah! You don’t have to worry about what type of elements you put in the List. You can put whatever you want in the List.
We run into big trouble when we try to pull elements out of a List and use them.
List list = new ArrayList();
list.add("Silent King II.");
list.add(18);
list.add(new RawType());
for (Object o : list ) {
String s = (String) o;
System.out.println(s);
}
Copy the code
The above code compiles without any problems, but when printed it throws a ClassCastException.
King of Silence 2 Exceptionin thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at com.cmower.java_demo.programcreek.RawType.main(RawType.java:14)
Copy the code
Unless we use the instanceof keyword for type determination, as follows.
List list = new ArrayList();
list.add("Silent King II.");
list.add(18);
list.add(new RawType());
for (Object o : list ) {
if (o instanceof String) {
String s = (String) o;
System.out.println(s);
} else if (o instanceof Integer) {
Integer i = (Integer) o;
System.out.println(i);
} else if (o instanceofRawType) { RawType raw = (RawType) o; System.out.println(raw); }}Copy the code
But if the code is written like this, it’s really bad code.
In general, for the sake of code security, we want code errors to occur as early as possible, rather than at run time, when they can be compiled. When primitive types are available, we find that errors may not be detected until runtime.
Do you still remember the story of Bian Que seeing Huan Gong of CAI?
Bian Que saw Duke Huan of CAI and set up a court. Bian Que said: “You have a disease in Cou, do not treat will fear deep.” Marquis Huan said, “I have no disease.” Bian Que went out, Marquis Huan said, “A good doctor can treat a disease without merit.” . On the tenth day, Bian Que visited Marquis Huan and left. Marquis Huan therefore made people ask it. Bian Que said: “The disease is striking cou rationale. In the skin, needle stone and also; In the stomach and stomach, fire is also reached; In the bone marrow, the fate of the department, helpless also. Now in the bone marrow, I am also without please.” On the fifth day, Marquis Huan suffered from physical pain and fled to Qin. Hou Sui died.
The earlier the disease is detected, the more likely it is to be treated. Similarly, the later a hidden problem is discovered, the more effort and time it takes to find the root cause.
What’s a better choice?
If you can’t use primitive types, what’s a better choice?
To make a List capable of containing any type of element, we can use List
List<Object> list = new ArrayList<>();
list.add("Silent King II.");
list.add(18);
list.add(new RawType());
Copy the code
Goose goose goose, is there a difference between such a parameterized List
Of course there is!
List
I may get some flak for this explanation: “Isn’t the pot calling the kettle black? Ha ha.” But I want to express what Neil Armstrong said: “That’s one small step for man, one giant leap for mankind.” One step forward is one step forward.
So what’s the optimal choice?
Declaring a specific type for a List from the beginning, such as List
List, will cause compilation errors when we try to put an int.
On another level, this reduces the flexibility of the program, but ensures absolute security and clarity of expression.
04. Why Java allows primitive types?
If primitive types are not safe, why does Java always allow primitive types? And the generic is still a primitive type after being erased?
The answer is simple, irrational, and pale — for version compatibility!
When generics were introduced, Java was well into its second decade (old) and there was a lot of code out there that didn’t use Java generics. If they don’t work because of a version upgrade, I’m afraid Java won’t survive as long as it does now, after all, user friendliness is the only reason software exists.
Of course, Java has issued a warning to developers: it is strongly recommended not to use primitive types in Java code, and they may be banned in future releases, so be careful.
05, thanks
Well, readers, that’s all for this article. Can see here are the most excellent programmers, two elder brother must move to start for you a praise 👍. If you don’t like it and want to see more, I recommend a few more.
50 w + programmers focus on the question: why ArrayIndexOutOfBoundsException will happen?
188W+ programmers: Is Java passed by value or by reference?
250W+ Programmer questions: What is a NullPointerException?
370W+ Programmer concerns: How do Java strings compare?
Have a harvest? Just like it, leave a comment and let more people see it.
If you want to see my updated articles for the first time, you can search “Silent King ii” on wechat, follow my official account, reply to “Java” and send you a gift package of selected e-books, including the best Java books I have read in the past ten years.