Learn from the java-15.1 filling containers (1)-Using the collection constructor

Source: Internet
Author: User

In this section we will introduce the filling container.

Just like an array, Arrays.fill is a fill method, which is also found inside the container.

1.collections.ncopies

This method is to generate a certain type of object, and then we can put it into the container's constructor. Fill the container.

Examples:

Package Com.ray.ch15;import Java.util.arraylist;import Java.util.collections;import java.util.linkedlist;public Class Test {public static void main (string[] args) {arraylist<integer> list = new Arraylist<integer> (collecti Ons.ncopies (5,1)); for (int i = 0; i < list.size (); i++) {System.out.print (List.get (i) + "");} linkedlist<integer> LinkedList = new Linkedlist<integer> (Collections.ncopies (6, 2)); for (int i = 0; I < Lin Kedlist.size (); i++) {System.out.print (Linkedlist.get (i) + "");}}}


Output:

1 1 1 1 1 2 2 2 2 2 2


2.fill

The fill here is not to be confused by his name. Its role is to replace objects inside the container.

Package Com.ray.ch15;import Java.util.arraylist;import Java.util.collections;public class Test {public static void main (string[] args) {arraylist<integer> list = new Arraylist<integer> (collections.ncopies (5,1)); for (int i = 0; i < list.size ( ); i++) {System.out.print (List.get (i) + "");} System.out.println (); Collections.fill (list, 2), for (int i = 0; i < list.size (); i++) {System.out.print (List.get (i) + "");}}}

Output:

1 1 1) 1 1
2 2 2) 2 2


Summary: This section describes how to populate the container and describes the Fill method.


This chapter is here. Thank you.

-----------------------------------

Folder





Learn from the java-15.1 filling containers (1)-Using the collection constructor

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.