String 클래스는 + 연산자를 어떻게 재정의합니까?
Java에서 String이 클래스 일 때 + 연산자를 사용하여 String을 추가 할 수있는 이유는 무엇입니까? 에서 String.java
코드 나는이 연산자에 대한 구현을 찾을 수 없습니다. 이 개념이 객체 방향을 위반합니까?
자바에서 다음과 같은 간단한 표현을 봅시다
int x=15;
String temp="x = "+x;
컴파일러는 내부적 "x = "+x;
으로 변환 하고 정수를 문자열에 "추가"하는 StringBuilder
데 사용 .append(int)
합니다.
문자열 변환을 통해 모든 형식을 문자열 형식으로 변환 할 수 있습니다.
프리미티브 유형 T의 값 x는 먼저 적절한 클래스 인스턴스 작성 표현식 (§15.9)에 인수로 제공하여 참조 값으로 변환됩니다.
- T가 부울 인 경우 new Boolean (x)을 사용하십시오.
- T가 char이면 new Character (x)를 사용하십시오.
- T가 byte, short 또는 int이면 new Integer (x)를 사용하십시오.
- T가 길면 new Long (x)를 사용하십시오.
- T가 float이면 new Float (x)를 사용하십시오.
- T가 double이면 new Double (x)를 사용하십시오.
그런 다음이 참조 값은 문자열 변환에 의해 문자열 유형으로 변환됩니다.
이제 참조 값만 고려하면됩니다.
- 참조가 널이면 문자열 "null"(4 개의 ASCII 문자 n, u, l, l)로 변환됩니다.
- 그렇지 않으면, 인수없이 참조 된 객체의 toString 메소드를 호출하는 것처럼 변환이 수행됩니다. 그러나 toString 메소드를 호출 한 결과가 널이면 문자열 "null"이 대신 사용됩니다.
toString 메소드는 기본 클래스 Object (§4.3.2)에 의해 정의됩니다. Boolean, Character, Integer, Long, Float, Double 및 String과 같은 많은 클래스가이를 재정의합니다.
문자열 변환 컨텍스트에 대한 자세한 내용은 §5.4를 참조하십시오.
문자열 연결 최적화 : 구현은 중간 문자열 개체를 생성 한 다음 폐기하지 않기 위해 한 단계로 변환 및 연결을 수행하도록 선택할 수 있습니다. 반복되는 문자열 연결의 성능을 높이기 위해 Java 컴파일러는 StringBuffer 클래스 또는 유사한 기술을 사용하여 표현식 평가에 의해 생성 된 중간 String 객체 수를 줄일 수 있습니다.
프리미티브 유형의 경우 구현시 기본 유형에서 문자열로 직접 변환하여 랩퍼 오브젝트 작성을 최적화 할 수도 있습니다.
최적화 된 버전은 실제로 전체 랩핑 된 문자열 변환을 먼저 수행하지 않습니다.
이것은 프리미티브를 변환하지 않아도 컴파일러가 사용하는 최적화 된 버전을 잘 보여줍니다. 컴파일러가 백그라운드에서 StringBuilder로 변경하는 것을 볼 수 있습니다.
http://caprazzi.net/posts/java-bytecode-string-concatenation-and-stringbuilder/
이 자바 코드 :
public static void main(String[] args) {
String cip = "cip";
String ciop = "ciop";
String plus = cip + ciop;
String build = new StringBuilder(cip).append(ciop).toString();
}
이것을 생성합니다-두 연결 스타일이 어떻게 같은 바이트 코드로 이어지는 지보십시오.
L0
LINENUMBER 23 L0
LDC "cip"
ASTORE 1
L1
LINENUMBER 24 L1
LDC "ciop"
ASTORE 2
// cip + ciop
L2
LINENUMBER 25 L2
NEW java/lang/StringBuilder
DUP
ALOAD 1
INVOKESTATIC java/lang/String.valueOf(Ljava/lang/Object;)Ljava/lang/String;
INVOKESPECIAL java/lang/StringBuilder.<init>(Ljava/lang/String;)V
ALOAD 2
INVOKEVIRTUAL java/lang/StringBuilder.append(Ljava/lang/String;)Ljava/lang/StringBuilder;
INVOKEVIRTUAL java/lang/StringBuilder.toString()Ljava/lang/String;
ASTORE 3
// new StringBuilder(cip).append(ciop).toString()
L3
LINENUMBER 26 L3
NEW java/lang/StringBuilder
DUP
ALOAD 1
INVOKESPECIAL java/lang/StringBuilder.<init>(Ljava/lang/String;)V
ALOAD 2
INVOKEVIRTUAL java/lang/StringBuilder.append(Ljava/lang/String;)Ljava/lang/StringBuilder;
INVOKEVIRTUAL java/lang/StringBuilder.toString()Ljava/lang/String;
ASTORE 4
L4
LINENUMBER 27 L4
RETURN
위의 예제와 주어진 예제의 소스 코드를 기반으로 한 바이트 코드가 생성되는 방식을 살펴보면 컴파일러가 내부적으로 다음 명령문을 변환했음을 알 수 있습니다.
cip+ciop;
으로
new StringBuilder(cip).append(ciop).toString();
다시 말해서, +
문자열 연결 의 연산자 는 더 자세한 StringBuilder
관용구 의 약칭입니다 .
It is Java compiler feature which checks the operands of +
operator. And based on the operands it generates the byte code:
- For String, it generates code to concat strings
- For Numbers, it generates code to add numbers.
This is what the Java spec says:
The operators + and
-
are called the additive operators. AdditiveExpression: MultiplicativeExpression AdditiveExpression + MultiplicativeExpression AdditiveExpression - MultiplicativeExpressionThe additive operators have the same precedence and are syntactically left associative (they group left-to-right). If the type of either operand of a
+
operator isString
, then the operation is string concatenation.Otherwise, the type of each of the operands of the
+
operator must be a type that is convertible (§5.1.8)to a primitive numeric type, or a compile-time error occurs.In every case, the type of each of the operands of the binary
-
operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs.
How String class overrides + operator?
It doesn't. The compiler does it. Strictly speaking, the compiler overloads the + operator for String operands.
First of all (+) is overloaded not overridden
The Java language provides special support for the string concatenation operator (+), which has been overloaded for Java Strings objects.
If left hand side operand is String it works as concatenation.
If left hand side operand is Integer it works as addition operator
The Java language provides special support for the string concatenation operator (+) and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder
(or StringBuffer
) class and its append
method.
The meaning of the +
operator when applied to String
is defined by the language, as everyone has written already. Since you don't seem to find this sufficiently convincing, consider this:
Ints, floats and doubles all have different binary representations, and therefore adding two ints is a different operation, in terms of bit manipulation, than adding two floats: For ints you can add bit by bit, carrying a bit and checking for overflow; for floats you must deal with the mantissas and exponents separately.
So, in principle, "addition" depends on the nature of the objects being "added". Java defines it for Strings as well as ints and floats (longs, doubles, ...)
The +
operator is usually replaced by a StringBuilder
at compile time. Check this answer for more details on that matter.
참고URL : https://stackoverflow.com/questions/11408427/how-does-the-string-class-override-the-operator
'programing tip' 카테고리의 다른 글
try catch finally 블록 내에서 돌아 오는 것은 나쁜 습관입니까? (0) | 2020.07.06 |
---|---|
무엇입니까 !! (0) | 2020.07.06 |
Illustrator에서 웹용 SVG를 내보내는 데 가장 적합한 설정은 무엇입니까? (0) | 2020.07.06 |
C ++에서 std :: function 또는 함수 포인터를 사용해야합니까? (0) | 2020.07.06 |
숫자를 고정 너비로 지정하고 앞에 0이 붙습니다. (0) | 2020.07.06 |