Pick a random element from an array

Swift 4.2 and above The new recommended approach is a built-in method on the Collection protocol: randomElement(). It returns an optional to avoid the empty case I assumed against previously. let array = [“Frodo”, “Samwise”, “Merry”, “Pippin”] print(array.randomElement()!) // Using ! knowing I have array.count > 0 If you don’t create the array and aren’t … Read more

Array.push() if does not exist?

For an array of strings (but not an array of objects), you can check if an item exists by calling .indexOf() and if it doesn’t then just push the item into the array: var newItem = “NEW_ITEM_TO_ARRAY”; var array = [“OLD_ITEM_1”, “OLD_ITEM_2”]; array.indexOf(newItem) === -1 ? array.push(newItem) : console.log(“This item already exists”); console.log(array)

How can I create an Array of ArrayLists?

As per Oracle Documentation: “You cannot create arrays of parameterized types” Instead, you could do: ArrayList<ArrayList<Individual>> group = new ArrayList<ArrayList<Individual>>(4); As suggested by Tom Hawting – tackline, it is even better to do: List<List<Individual>> group = new ArrayList<List<Individual>>(4);

Android- create JSON Array and JSON Object

Use the following code: JSONObject student1 = new JSONObject(); try { student1.put(“id”, “3”); student1.put(“name”, “NAME OF STUDENT”); student1.put(“year”, “3rd”); student1.put(“curriculum”, “Arts”); student1.put(“birthday”, “5/5/1993”); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } JSONObject student2 = new JSONObject(); try { student2.put(“id”, “2”); student2.put(“name”, “NAME OF STUDENT2”); student2.put(“year”, “4rd”); student2.put(“curriculum”, “scicence”); student2.put(“birthday”, “5/5/1993”); } … Read more