Convert list to array in Java [duplicate]

Either: or: Note that this works only for arrays of reference types. For arrays of primitive types, use the traditional way: Update: It is recommended now to use list.toArray(new Foo[0]);, not list.toArray(new Foo[list.size()]);. From JetBrains Intellij Idea inspection: There are two styles to convert a collection to an array: either using a pre-sized array (like … Read more

Loop through an array in JavaScript

Three main options: for (var i = 0; i < xs.length; i++) { console.log(xs[i]); } xs.forEach((x, i) => console.log(x)); for (const x of xs) { console.log(x); } Detailed examples are below. 1. Sequential for loop:  Run code snippet Pros Works on every environment You can use break and continue flow control statements Cons Too verbose Imperative Easy to have off-by-one errors (sometimes also … Read more

How do I declare and initialize an array in Java?

You can either use array declaration or array literal (but only when you declare and affect the variable right away, array literals cannot be used for re-assigning an array). For primitive types: For classes, for example String, it’s the same: The third way of initializing is useful when you declare an array first and then … Read more

How to split a string into an array in Bash?

Note that the characters in $IFS are treated individually as separators so that in this case fields may be separated by either a comma or a space rather than the sequence of the two characters. Interestingly though, empty fields aren’t created when comma-space appears in the input because the space is treated specially. To access … Read more

Loop through an array in JavaScript

Yes, assuming your implementation includes the for…of feature introduced in ECMAScript 2015 (the “Harmony” release)… which is a pretty safe assumption these days. It works like this: Or better yet, since ECMAScript 2015 also provides block-scoped variables: (The variable s is different on each iteration, but can still be declared const inside the loop body as long as it isn’t modified there.) A … Read more

How do I find the length of an array?

If you mean a C-style array, then you can do something like: This doesn’t work on pointers (i.e. it won’t work for either of the following): or: In C++, if you want this kind of behavior, then you should be using a container class; probably std::vector.