Use of generics in Java collections

Source: Internet
Author: User

Use of generics in Java collections

Generics provide a lightweight and flexible data operation, and the security of the data is relatively improved.

Generics provide constraints on list elements, such as ArrayList ordered linked lists, which can store any type of element.

A ArrayList object is built here.

New ArrayList ();

You can add elements of any data type to the list list by using the List.add () method, such as:

       List.add (1);       List.add ("str");       List.add (true);       = list.iterator ();         while (It.hasnext ()) {            System.out.println (It.next ());        }

After the compiler compiles, the output is:

1

Str

True

However, if a generic is used to ArrayList a data constraint, such as ArrayList, it means that only values of type int are allowed to be stored in the ArrayList linked list.

New ArrayList 
   
     ();
   

You can add elements of any data type to the list list by using the List.add () method, such as:

        List.add (1);        // list.add ("str"); This type is string and the compiler will error        // List.add (TRUE); This type is a Boolean compiler will error, so comment out = list.iterator ();                while (It.hasnext ()) {            System.out.println (It.next ());        }    

After the compiler compiles, the output is:

1

Visible generics can have a data constraint, which improves the convenience and security of data manipulation.

Use of generics in Java collections

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.