Java Reference
In-Depth Information
Note that this changes the order of the array permanently.
Sort
We can sort the order of an array using the sort() method:
pizzas.sort();
<< ["Chicken & Bacon", "Chicken and Mushroom", "Ham &
Mushroom"
, "Mushroom", "Spicy Beef", "Veggie Deluxe"]
It is alphabetical order by default for String objects. Note that this also changes the order
of the array permanently.
Warning: Numbers Are Sorted Alphabetically
Numbers are also sorted alphabetically, so 9 will come after 10 when you
try to sort an array of numbers:
[5, 9, 10].sort();
<< [10, 5, 9]
This can be fixed using a special type of function called a callback . We'll
cover how to do this in Chapter 4.
Finding if a Value is in an Array
We can find out if an array contains an object using the indexOf() method to find the
first occurrence of a value in an array. If the item is in the array, it will return the index of
the first occurrence of that item:
pizzas.indexOf("Spicy Beef");
<< 4
If the item is not in the array, it will return -1 :
Search WWH ::




Custom Search