You are on page 1of 24

LESSON 9 – ADVANCED

ARRAY CONCEPTS
Sorting Array Elements
 Sorting
 Ascending
 Descending
 bubble sort
 Comparing 2 elements and then swapping them if not
in order
Do Bubble Sorting
 int[] someNums = {88, 33, 99, 22, 54};
 With the numbers 88, 33, 99, 22, and 54, the
process proceeds as follows:
 Compare 88 and 33. They are out of order. Swap
them. The list becomes 33, 88, 99, 22, 54.
 Compare the second and third numbers in the list—
88 and 99. They are in order. Do nothing.
Do bubble sorting
 Compare the third and fourth numbers in the list—
99 and 22. They are out of order. Swap them. The
list becomes 33, 88, 22, 99, 54.
 Compare the fourth and fifth numbers—99 and 54.
They are out of order. Swap them.
 The list becomes 33, 88, 22, 54, 99.
Using Two-Dimensional and Other
Multidimensional
Arrays

SINGLE DIMENSION
MULTI
DIMEN
SION
Declaring Multi Dimensional Array

 int[][] someNumbers = new int[3][4];

Row/Col
0 1 2 3
0
1
2
Using the Arrays Class
Sample Arrays Class
Using the ArrayList Class
 Array List
 dynamically resizable
 How to Import?
 import java.util.ArrayList;
 import java.util.*;
 ArrayList names = new ArrayList();
ArrayList Methods
Sample
Output
Another Example
Output
Limitations of ArrayList
 You cannot use an ArrayList to store primitive
types such as int, double, or char because those
types are not references.
 When you want to store ArrayList elements, you
must cast them to the appropriate reference type
before you can do so, or you must declare a
reference type in the ArrayList declaration.
Example
 String firstName;
 firstName = (String)names.get(0);

 To prevent casting, use this


 ArrayList<String> names = new ArrayList<String>();
Advantages of ArrayList declaration

 No longer use of the cast operator


 Java checks to make sure that only items of the
appropriate type are added to the list
 The compiler warning that indicates your program
uses an unchecked or unsafe operation is
eliminated.
Creating Enum
 A programmer created data type with a fixed set of
values
 Enumerated data types
 Pair of curly braces that contain a list
 Enum constants
Example
 Declare Enum:
 enum Month {JAN, FEB, MAR, APR, MAY, JUN,
JUL, AUG, SEP, OCT, NOV, DEC};
 Use Enum
 Month birthMonth;
 birthMonth = Month.MAY;
Enum non-static Functions
Enum static functions
Sample
Output
Sample

You might also like