Understanding Java "final" for C # Translation

I am not a Java programmer. I read the documentation for "final" and understand that "the value of a variable can be set once and only once."

I translated some Java in C #. The code does not execute as expected. I tried to find out why, and found some use cases for the ending that didn't make sense.

Code Snippet 1:

final int[] PRED = { 0, 0, 0 };
...
PRED[1] = 3;

Will PRED [1] be 0 or 3?

Code Snippet 2:

final int[] PRED = new int[this.Nf];
for (int nComponent = 0; nComponent < this.Nf; nComponent++) {
    PRED[nComponent] = 0;
}
...
PRED[1] = 3;

Of course, PRED [0] will remain 0 0

+5
source share
6 answers

I think you misunderstand the semantic keyword finalwhen applied to arrays in Java.

Java , . , , , . ,

final int[] PRED = new int[this.Nf];
// some other code
PRED = new int[123]; // <<== Compile error

.

# final sealed ( class), readonly ( ). readonly # final Java : , .

, Java-, final , #: Java, final. # , - , , . readonly.

+6

, #, "const":

const int SOMETHING = 10;

, SIZE .

, int, bool, string, char .. ( ).

, - , , :

static readonly int[] PRED = new int[this.Nf];

Readonly const, , , - , . ( - readonly's)

, :

PRED = new int[3]; // Error
PRED = null; // Error
PRED = PRED; // Error

INSIDE PRED:

PRED[0] = 123;

, ReadOnlyCollection! , , static-readonly ( , ), :

static readonly ReadOnlyCollection<int> PRED = new ReadOnlyCollection<int>(new[] {1, 2, 5, 6});

PRED PRED 4 1, 2, 5, 6.

PRED = PRED; // Error (static readonly)
PRED = null; // Error (static readonly)
PRED[1] = 0; // Error (ReadOnlyCollection enforces readonly on the elements)

int i = PRED[1]; // Still works, since you aren't changing the collection.
+3

final , . , PRED[1] = 3 , , .

, final : . : , .

PRED. PRED[1]. PRED , PRED.set(1, 3). . , , PRED = new ArrayList<Integer>().

+2

, , final java readonly # const, , , , , ;)

+1

, final ​​. .

+1

Java final Java . :

  • To declare a constant variable,
  • Declare a constant method parameter.

    • A variable declared as final must have initialization before it is used. This variable cannot be assigned a new value, such as (a = b). But if the variable does not have a primitive type, then its properties can be set using the set methods or any other public fields. This means that the reference to the object instance cannot be changed, but the properties of the object instance can be changed if they themselves are not declared final.

    • Disallow a parameter that changes in the method in which it is used.

+1
source

All Articles