"Bagaimana kalau saya mulai dengan apa yang benar-benar berguna? Sekarang Anda akan melihat beberapa cara agar ArrayList dan generik dapat digunakan:"

"Contoh 1:"

Baca daftar nomor dari keyboard
``````public static void main(String[] args) throws IOException
{
ArrayList<Integer> list = new ArrayList<Integer>() ;

while (true)
{
if (s.isEmpty()) break;
}
}``````

"Contoh 2:"

Sama seperti di atas, tetapi angka genap ditambahkan di akhir daftar, ganjil – di awal daftar.
``````public static void main(String[] args) throws IOException
{
ArrayList<Integer> list = new ArrayList<Integer>();

while (true)
{
if (s.isEmpty()) break;

int x = Integer.parseInt(s);
if (x % 2 == 0)  // Check that the remainder is zero when we divide by two
else
}
}``````

"Contoh 3:"

Hapus semua angka yang lebih besar dari 5:
``````public static void main(String[] args) throws IOException
{
ArrayList<Integer> list = new ArrayList<Integer>();

for (int i = 0; i < list.size(); ) // We moved the statement that increases i to inside the loop
{
if (list.get(i) > 5)
list.remove(i);  // Don’t increase i if we deleted the current element
else
i++;
}
}``````

"Contoh 4:"

Membagi array menjadi dua bagian - angka genap dan ganjil
``````public static void main(String[] args) throws IOException
{
// Static initialization of the array
int[] data = {1, 5, 6, 11, 3, 15, 7, 8};

// Create a list where all elements are Integers
ArrayList<Integer> list = new ArrayList<Integer> ();

// Use the array to fill the list
for (int i = 0; i < data.length; i++) list.add(data[i]);

ArrayList<Integer> even = new ArrayList<Integer>();  // Even numbers
ArrayList<Integer> odd = new ArrayList<Integer>();    // Odd numbers

for (int i = 0; i < list.size(); i++)
{
Integer x = list.get(i);
if (x % 2 == 0)    // If x is even
else
}
}``````

"Contoh 5:"

Gabungkan daftar
``````public static void main(String[] args) throws IOException
{
ArrayList<Integer> list1 = new ArrayList<Integer>();   // Create a list
Collections.addAll(list1, 1, 5, 6, 11, 3, 15, 7, 8);   // Fill the list

ArrayList<Integer> list2 = new ArrayList<Integer>();
Collections.addAll(list2, 1, 8, 6, 21, 53, 5, 67, 18);

ArrayList<Integer> result = new ArrayList<Integer>();

result.addAll(list1);   // Add all values from each list to the new list