java - Ensure capacity of List -


i browsing how create own list , landed on site http://www.vogella.com/tutorials/javadatastructurelist/article.html had below method.

private void ensurecapa() {     int newsize = elements.length * 2;     elements = arrays.copyof(elements, newsize); } 

i found similar methods in many other sites , understood ensurecapacity does. don't understand why length multiplied 2 (elements.length * 2). there specific reason or vary data type?

thanks in advance.

doubling capacity of list when it's full done couple of reasons.

as @jheimbouch , @user3437460 stated, kinda makes sense intuitively. you'd want increase in proportional amount current size of list. adding few fixed elements @ end each time end being bad big fat list.

it's more efficent in general. if don't have idea of size list going (as when designing own array-based list class general use), if double size of list each time, on average on each large set of insertions, each insert take o(1) constant time (this called amortized constant time operation).

think it, cost of resizing array n. thing can adjust how that. more it, more tightly bound our array our actual data size, use less memory. less it, save on cpu cycles.

there's proofs abound regarding time complexity, here's 1 found http://anh.cs.luc.edu/363/notes/06a_amortizing.html

long story short, it's mathematically sound in general case, , strikes balance between memory consumption , processing time.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -