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.
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.
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.