What is Impossible in Java?

Asked 2 years ago, Updated 2 years ago, 60 views

Impossible is not well understood. Please explain with an example.

string java immutability

2022-09-22 14:17

1 Answers

Impossible is an object that cannot be changed after creation. So there is no set method for immutable. Cannot change member variable. There is no method with return type void. Usually, the void method may or may not do something. ) Because it plays a role in changing member variables, it is rarely used. (Of course, there may be exceptional voids, such as shooting something on the console.) With Imutable, it's easier to create more reliable code in a multi-threaded environment. If you've worked with a multi-threaded program, you'll know that in a multi-threaded environment, abnormal operation is more common than error. It's hard to find because it's not an error. Besides, it doesn't happen all the time, and it's not once or twice that I have a headache because I have a problem once a year. If you use Imutable, you can reduce these factors a lot.

There are String, Boolean, Integer, Float, Long, etc. It is important to note that it is impossible to change in the heap area. You can reallocate as shown in Stringa="a";a="b";. This changes the object in the heap area where a is referenced, not the value in the heap area.

String and StringBuffer have many similar mesods, so they look similar, but there is a decisive difference. String is Impossible. Not StringBuffer. Have you heard that StringBuffer is much faster than String? That's because you don't need to create a new object.

The representative mesodes that are not in String but only in String Buffer will be append, delete, etc. You can change the value by changing the member variable. But if you look carefully, their return is the String Buffer type. If they create a new object anyway, it doesn't look much different from String. However, you are not creating a new object. Try executing the code below.

StringBuffer b = new StringBuffer();
StringBuffer a = b.append("test");
System.out.println(a == b);

It says true. It is not a new object, but a return this. The reason for returning seems to be to enable coding as below.

StringBuffer test = new StringBuffer();
test.append("a").append("b").append("c").append("d");

I think it's trying to make it possible to code multiple lines in one line like this. Or not.-_-;

In a multi-threaded environment, access to one object may not be affected by each thread. At that time, it would be convenient if it was guaranteed that the value of the object once created would not change.

String a  = "";
while
    a += "Machine";
    If (another conditional statement) {
        break;
    }
}

Do not write the above code. The a+= "Machine" syntax is a problem. Continue to create objects. If you write where the value can continue to change, Imutable consumes a lot of memory. After the values are completely cleared, you must create them as executable in one queue. (Of course, it's not a deadly dangerous level of behavior because garbage collection rotates and organizes it.)

There are unmodifiable machine methods in java.util.Collections. If you use these, you can use Set, List, Map, etc. as executable. However, UnsupportedOperationException occurs when a method such as add or put is called. Exception situations should be considered.

When I first did Java, I wanted to add a method called ltrim to the object called String. (Only the left trim is a mesod.) I tried to create a new class by inheriting it. Oh, but it's defined as final, so you can't inherit it. If it is not defined as final, the inherited class may break Impossible.

package immutable;

import java.text.SimpleDateFormat;
import java.util.Date;

public final class WrongImmutable {
    private final Date date;
    private final SimpleDateFormat dateFormat;
    public WrongImmutable(Date date){
        this.date = date;
        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }
    public String getMessage(){
        return dateFormat.format(date);
    }
}

Look at the sauce above. The variable date is defined as final, and there is no setter, so it seems that only the constructor can specify a value. However, if you run the test class below, you can see that the code above is wrong.

package immutable;

import java.util.Date;

public class WrongImmutableTest {
    public static void main(String[] args) {
        Date testDate = new Date();
        WrongImmutable wrongImmutable = new WrongImmutable(testDate);
        testDate.setTime(testDate.getTime() + 10000000);
        System.out.println(wrongImmutable.getMessage());
    }
}

Changing the value of the member variable of WrongImutable from the outside of Date that you factor in the constructor of WrongImutable changes the value of the member variable. In Immutable, the member variable must not be externally open and can be changed. Then, in order to make it as normal as you initially wanted, you must copy and write in some way rather than just using the Date object that you received as a factor. The part of the constructor that assigns the value of the member variable.

this.date = new Date(date.getTime()); You have to change it like this.

You can change it by using the reflection of java. Try running the following code.

import java.lang.reflect.Field;

public class EditUsingReflection {
    public static void main(String[] args) throws IllegalArgumentException, SecurityException, IllegalAccessException, NoSuchFieldException {
        String s = "string!";
        edit(s);
        System.out.println(s);
    }
    public static void edit(String s) throws IllegalArgumentException, IllegalAccessException, SecurityException, NoSuchFieldException {
        Field stringValue = String.class.getDeclaredField("value");
        stringValue.setAccessible(true);
        stringValue.set(s, s.toUpperCase().toCharArray());
    }
}

String objects manage their values internally with char[] named value. It's declared private, of course. Reflection allows you to ignore and approach the private in the member variable. In the end, reflection can be used to modify all member variables. Impossible is only possible when you think about it without reflection.

http://egloos.zum.com/iilii/v/3809685


2022-09-22 14:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.