Can I use short as an index for an array?

In java or swift, it is safe to use short on array index like

short r = 2;
System.out.println(myArray[r]);

      

We usually use int for this, but the idea of ​​using the short has never crossed my path until now.

+3


source to share


2 answers


It's safe? Yes. I would not recommend it. People copy / paste code all the time. You can copy usage short

in a loop.

Arrays in java have maximum size Integer.MAX_VALUE

, so if you have to write



for(short s = 0; s < array.length; s++) { // ... }

You end up with an overflow, because the length of the array may be longer.

+4


source


Generally, there is no need to use it short

as an array index. You can also use byte

as array index . But you only need to remember that the array index cannot be negative.



There short

are 16 bits or 2 bytes in java . Thus, it is long enough to be used as an array index in a normal situation.

0


source







All Articles