参数列表含重复原始类型名称的方法(如String String)的写法原因及含义咨询
(String String) as Parameters? Great question—this is a common point of confusion because it looks counterintuitive at first glance. Let’s break this down clearly:
1. Is This Syntax Legal?
Yes, it is! In Java (the language of your example), identifiers like parameter names just need to follow basic rules: they can’t be reserved keywords (like int, class, return), and they have to start with a letter, underscore, or dollar sign.
String isn’t a keyword—it’s the name of the java.lang.String class. So using it as a parameter name is allowed by the compiler.
2. What Does (String String) Actually Mean?
Let’s parse it like the compiler does:
- The first
Stringis the type of the parameter (it tells the compiler this parameter holds aStringobject). - The second
Stringis the variable name of the parameter—this is what you’ll use inside the method to refer to the value passed in.
It’s exactly equivalent to writing (String str) or (String myString)—the only difference is the variable name is identical to the type name.
3. Why Is This a Terrible Idea?
While it’s legal, this is a horrible coding practice for a few key reasons:
- Readability disaster: Anyone reading the code will immediately confuse the type with the variable. It makes the code harder to scan and understand.
- Name shadowing issues: Inside the method, the parameter name
String"shadows" the class namejava.lang.String. That means if you try to use theStringclass (like callingString.valueOf(42)), the compiler will think you’re referring to the parameter variable instead of the class. You’ll have to write the full qualified namejava.lang.String.valueOf(42)to make it work, which is tedious and error-prone. - Team conventions: No professional team allows this kind of naming—it violates every standard coding style guide (like Oracle’s Java Code Conventions or Google’s Java Style Guide).
Example of the Shadowing Problem
Here’s how this causes issues in practice:
public static void print(String String) { // This works: we're referring to the parameter variable System.out.println("Parameter value: " + String); // This will throw a compile error! // Compiler thinks "String" is the parameter, not the class // String defaultStr = String.valueOf("default"); // To fix it, you have to use the full class name java.lang.String defaultStr = java.lang.String.valueOf("default"); }
Final Takeaway
Your school’s example is probably either demonstrating what’s syntactically allowed (even if it’s bad practice) or it’s a typo. Either way, you should never write code like this in real projects—stick to descriptive, distinct variable names (like str, input, or message) to keep your code clean and maintainable.
内容的提问来源于stack exchange,提问作者kai




