Getting started with java-15.1 filling containers (2)
Next, let's continue with the section on filling containers.
This chapter ends with another method of filling the container: addAll
Example:
Package com. ray. ch15; import java. util. arrayList; import java. util. arrays; import java. util. linkedHashSet; public class Test {public static void main (String [] args) {MyCollection
MyCollection = new MyCollection
(New MyGenerator (), 25); // Fill System. out. println (Arrays. toString (myCollection. toArray () in the constructor; then hashset
Set = new LinkedHashSet
(MyCollection); System. out. println (Arrays. toString (set. toArray (); set. clear (); set. addAll (myCollection); // another method is System. out. println (Arrays. toString (set. toArray ();} interface Generator
{T next ();} class MyCollection
Extends ArrayList
{Private static final long serialVersionUID = 1L; public MyCollection (Generator
Generator, int count) {for (int I = 0; I <count; I ++) {add (generator. next () ;}} class MyGenerator implements Generator
{Private String strPool = "The annual expansion rate for" + "industrial output will be around und 6 percent this year," + "well below this year's GDP growth, which is likely to be "+" about 7 percent, the Ministry of Industry and Information "+" Technology said, adding that such a situation was happening "+" for the first time in nearly two decades. "; private int index = 0; @ Overridepublic String next () {return strPool. split ("") [index ++] ;}}
Output:
[The, annual, expansion, rate, for, industrial, output, will, be, around]
[The, annual, expansion, rate, for, industrial, output, will, be, around]
[The, annual, expansion, rate, for, industrial, output, will, be, around]
Let me explain the above Code. There are several notes:
(1) Continue with the generators mentioned in the previous sections. We use generic generators to generate related objects. Objects created in this way are flexible. Unlike the nCopy method provided by the system, you can only create a single object.
(2) create a container of your own (inherited from Arraylist). It is used to load the objects created by the generator and inherit from a container. You can conveniently call the add method in the constructor, container features
(3) The main method shows two filling methods for containers. One is to add them directly in the constructor, and the other is to use the addAll method, both methods receive Collection containers, so we can add whatever containers are generated.
Summary: This chapter shows another way to fill the container.
This chapter is here. Thank you.
-----------------------------------
Directory