“This is the third day of my participation in the August More Text Challenge.

We covered ArrayList collections in the previous article, but in this article we will cover some exercises to use ArrayList collections.

Exercise 1(Storing random numbers)

Generate 10 random numbers between 1 and 55, add them to the set, and iterate over the output.

Let’s analyze this problem and give you an idea

1. 10 integers need to be stored, so create a <Integer> set 2. 3. Generate 10 Random numbers and use a loop. Within the loop, call random. nextInt(int x) with the parameter 55. 4. Add the generated random number to the collection. 6Copy the code

Let’s look at the code:

ArrayList<Integer> ArrayList = new ArrayList<>(); // create Random object Random Random = new Random(); Int I = 0; // Generate 10 random numbers from 1 to 55 i < 10; i++) { int randomNum = random.nextInt(55); Arraylist. add(randomNum); } // Use the for loop to iterate over the collection, printing for (int I = 0; i < arrayList.size(); i++) { System.out.println(arrayList.get(i)); }Copy the code

Exercise 2(Storing custom type objects in a collection)

Title: Add four Student objects to the collection and iterate over the output

Analysis:

Create Student class 2. Create a <Student> set 3. Add four Student objects to the collection. 4. Iterate through the collection and printCopy the code

Let’s look at the code:

ArrayList<Student> ArrayList = new ArrayList<>(); Student student1 = new Student("1","Tom"); Student student2 = new Student("2","Jack"); Student student3 = new Student("3","LiHua"); Student student4 = new Student("4","KangKang"); Arraylist.add (student1); // Add the Student object to the collection. arrayList.add(student2); arrayList.add(student3); arrayList.add(student4); For (Student Student: arrayList) {system.out.println (Student); }Copy the code

Exercise 3(Using collections as parameters)

Title: Define a method to print a collection in the specified format. Format: Add a “GW*” before printing the elements of each collection. The format here is arbitrary, but the key is to make sure you understand how to use collections as arguments to methods.

Look at the code:

public static void printArrayList(ArrayList<Student> arrayList){ for (Student student : arrayList) { System.out.println("GW*"+student); }}Copy the code

Okay, so that’s the end of the exercise, just to get you used to using ArrayList collections. Most important are the methods in the ArrayList collection, and the scenarios in which the collection is used. Here are some simple applications, and once you’re familiar with them, you can use ArrayList collections to apply them to more scenarios, so try it out for yourself!