"How about I start with what's actually useful? You'll now see a couple of ways that ArrayList and generics can be put to work:"

"Example 1:"

Read a list of numbers from the keyboard
``````public static void main(String[] args) throws IOException
{
ArrayList<Integer> list = new ArrayList<Integer>() ;

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

"Example 2:"

Same as above, but even numbers are added to the end of the list, odd – to the beginning of it.
``````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
}
}``````

"Example 3:"

Delete all numbers larger than 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++;
}
}``````

"Example 4:"

Divide an array into two parts – even and odd numbers
``````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&ltInteger> list = new ArrayList&ltInteger> ();

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

ArrayList&ltInteger> even = new ArrayList&ltInteger>();  // Even numbers
ArrayList&ltInteger> odd = new ArrayList&ltInteger>();    // Odd numbers

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

"Example 5:"

Merge lists
``````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

for (Integer x : result)   // A fast way to loop over all elements, only for collections
{
System.out.println(x);
}
}``````

"Cool! Will Diego now give me a truck load of similar exercises?"

"Yes, he will."

7
Опрос
Methods,  7 уровень,  8 лекция
недоступен
Methods
Methods