Why is this class considered mutable?

时间:2017-08-30 20:54:13

标签: java arrays immutability mutability

static int[] loops = new int[]{10000, 100000, 1000000};

static void useCharAt(String s){
    int sum = 0;
    for(int loop : loops) {
        long start = System.currentTimeMillis();
        for (int i = 0; i < loop; i++) {
            for (int j = 0; j < s.length(); j++) {
                sum += s.charAt(j);
            }
        }
        System.out.println("string size is " + s.length() + ", loop size is "+loop+", charAt() costs " + (System.currentTimeMillis() - start) + " ms");
    }
}

static void useArray(String s){
    char[] arr= s.toCharArray();
    int sum = 0;
    for(int loop : loops) {
        long start = System.currentTimeMillis();
        for (int i = 0; i < loop; i++) {
            for (char c : arr) {
                sum += c;
            }
        }
        System.out.println("string size is " + s.length() + ", loop size is "+loop+", array costs " + (System.currentTimeMillis() - start) + " ms");
    }
}

public static void main(String[] args){
    StringBuilder sb = new StringBuilder();
    int strLen[] = new int[]{1000, 5000, 10000};
    for(int len : strLen) {
        sb.setLength(0);
        for(int i = 0; i < len; i++) sb.append('a');
        String s = sb.toString();
        useArray(s);
        useCharAt(s);
    }
}

A book that I'm reading says that it is not immutable because values is a reference type. I see no way to mutate values other than creating a main method inside of the class.

4 个答案:

答案 0 :(得分:4)

It is mutable because you can change the contents of git rm --cached web/libraries/randomLibrary through the method that you exposed

 git add web/libraries/randomLibrary/*

This would mean that your git add --all && git commit -m "Message" property contains now information that has been modified externally. To make it immutable, you should return a copy of the array, so that you are sure no external agent can modify it, and you should make it final, so that no subclasses can be created that can expose the state and make it mutable again:

values

答案 1 :(得分:1)

It's not actually mutable through the <?php $route['register'] = 'register/index'; $route['register/(:any)'] = 'register/$1'; $route['news/create'] = 'news/create'; $route['news/(:any)'] = 'news/view/$1'; $route['news'] = 'news'; $route['pages/view/(:any)'] = 'pages/view/$1'; $route['default_controller'] = 'pages/view'; array, as stated in other answers: that array is /home/gerhard/Projects/bounzapp/node_modules/react-native-fbsdk/android/src/main/java/com/facebook/reactnative/androidsdk/FBSDKPackage.java:61: error: method does not override or implement a method from a supertype @Override ^, as it is never initialized, and you can't make it non-null via the result of the getter.

It's mutable because you can subclass it, and add mutable state:

gerhard@linux-clqp:~/Projects/bounzapp> react-native link
Scanning 680 folders for symlinks in /home/gerhard/Projects/bounzapp/node_modules (10ms)
rnpm-install info Android module react-native-fbsdk is already linked
rnpm-install info Linking react-native-fbsdk ios dependency
rnpm-install ERR! Something went wrong while linking. Error: Expected "/*", "//", or "{" but "<" found.
Please file an issue here: https://github.com/facebook/react-native/issues

Expected "/*", "//", or "{" but "<" found.

Note that there is a "Strategy for defining immutable objects" in the Oracle Java tutorial, as well as a list of requiried properties of immutable objects in Effective Java 2nd Ed Item 15: "Minimize mutability".

答案 2 :(得分:0)

You can get reference and change element array:

all

You can use reflection to change values field, or somewhere else (probably author means) or with inheritance as showed below.

For instance,

Immutable class:

True

Immutable object:

def a_sorting_function_of_some_sort(list_to_sort):
    while not all([all([number <= numbers_list[numbers_list.index(number) + 1] for number in numbers_list 
                        if not number == numbers_list[-1]]) 
                   for numbers_list in list_to_sort]):

        for numbers_list in list_to_sort:

            # There's nothing to do if the list contains just one number
            if len(numbers_list) > 1:
                for number in numbers_list:
                    number_index = numbers_list.index(number)
                    try:
                        next_number_index = number_index + 1
                        next_number = numbers_list[next_number_index]
                    # If IndexError is raised here, it means we don't have any other numbers to check against,
                    # so we break this numbers iteration to go to the next list iteration
                    except IndexError:
                        break
                    if not number < next_number:
                        numbers_list_index = list_to_sort.index(numbers_list)
                        list_to_sort.insert(numbers_list_index + 1, [*numbers_list[:number_index], number + next_number, 
                                                                     *numbers_list[next_number_index + 1:]])
                        numbers_list[number_index] = next_number
                        numbers_list[next_number_index] = number
                        # We also need to break after parsing unsorted numbers
                        break
    return list_to_sort

Immutable class and object:

 A.getValues()[0] = -100500

答案 3 :(得分:0)

PDDocument doc = generatePDF(name, v1, v2, v3, v4); ByteArrayOutputStream baos = new ByteArrayOutputStream(); doc.save(baos); byte[] pdfBytes = baos.toByteArray(); ,作为数组是引用类型。您可以找到有关参考here的更多信息。这意味着当values返回getValues()时,它实际上会返回一个指向它的指针(每次都会被取消引用,因为Java没有显式指针)。虽然由于values是私有的,但无法重新分配引用本身,因此可以更改内容。

values之类的内容会增加a.getValues()[0]++的第一个元素,假设它不是空的。