Is there an equivalent method in Javascript arrays or ArrayList to Java's ensureCapacity? I am translating a certain Java code containing this method to Javascript, and couldn't find any equivalent to it. Thanks in advance
asked Sep 24, 2014 at 11:51
elbereth
371 gold badge4 silver badges10 bronze badges
2 Answers 2
It is possible to initialize an array with a specific size:
var array = new Array(n);
If your array has already been initialized you can, as mentioned in comments, set the length of the array using the length property:
array.length = n;
However, the performance gains, if any, seems negligble. Here is a thread discussing this.
answered Sep 24, 2014 at 11:56
Frederik Wordenskjold
10.3k7 gold badges40 silver badges57 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
CodingIntrigue
And also set it via
array.lengthelbereth
So, for instance, if I am using it this way: public Path(int initialCapacity) { tsIindexes.ensureCapacity(initialCapacity); tsJindexes.ensureCapacity(initialCapacity); } would setting it with length amount to the same thing as done here?
Frederik Wordenskjold
Yeah, it would. But as mentioned, it is probably not necessary.
var fruits = ['apple', 'pineapple'];
console.log(fruits.length, fruits);//2 ["apple", "pineapple"]
fruits.length = fruits.length + 4; //increase by 4
console.log(fruits.length, fruits);//6 ["apple", "pineapple"]
Open console for more ...
answered Sep 24, 2014 at 11:58
user2575725
Comments
default
.length, but it doesn't make much difference.