Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use the List collection

Shulou Source: shulou.com Published: 2022-06-01 11:34:55 09月16日 Update

This article mainly explains "how to use the List collection". The content in the article is simple and clear, easy to learn and understand. Please follow the editor's train of thought to study and learn how to use the List collection.

List collection features: 1. Orderly. For example, the order in which elements are stored is 66, 88, 99. Then the storage of the elements in the collection is done in the order of 66, 88, 99). two。 There is an index. The elements in the collection can be precisely manipulated through the index (just like the index of an array). 3. The element repeats. Use the element's equals method to compare whether it is a duplicate element.

Common methods in List collection

As a subinterface of the Collection collection, List not only inherits all the methods in the Collection interface, but also adds some unique methods to manipulate the collection based on the element index, as follows:

Public void add (int index, E element): adds the specified element to the specified location in the collection. Public E get (int index): returns the element at the specified location in the collection. Public E remove (int index): removes the element at the specified position in the list and returns the removed element. Public E set (int index, E element): replaces the element at the specified location in the collection with the specified element, returning the element before the update of the value.

Example of List collection method:

Public class ListDemo {public static void main (String [] args) {/ / create List collection object List list = new ArrayList ()

/ / add specified elements list.add ("Xiao Zhan"); list.add ("Wang Yibo"); list.add ("Chen Li") to the tail

System.out.println (list); / / add (int index,String s) add list.add (1, "Cai Xukun") to the specified location

System.out.println (list); / / String remove (int index) Deletes the specified location element returns the deleted element / / deletes the element with index position 2 System.out.println ("Delete the element with index position 2"); System.out.println (list.remove (2))

System.out.println (list)

/ / String set (int index,String s) / / replace (change) the element at the specified location / / modify the specified location element list.set (0, "Wang Junkai"); System.out.println (list)

/ / String get (int index) gets the specified location element / / the for used to traverse with the size () method (int I = 0bot I)

Tags: Elements locations methods indexes data structures middle fingers storage learning development content stacks subclasses that is commonly used interfaces arrays order head and tail rigorous Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Shulou Information NVidia Docker Shulou Technology