Home Java javaTutorial Detailed explanation of java list usage examples

Detailed explanation of java list usage examples

Dec 12, 2016 pm 02:49 PM

|--List: The elements are in order (you can take them out as you want, the order will not be messed up), and the elements can be repeated (there can be a 3 on subscript 1, and there can also be a 3 on subscript 2) because of this The collection system has an index,
|-- ArrayList: The underlying data structure uses an array structure (the array length is variable and can be extended by 50%) (characteristically, the query is fast, but additions and deletions are slow) and the threads are not synchronized
|-- LinkedList: The underlying data structure is a linked list structure (characterized by slow query and fast addition and deletion)
|-- Vector: The underlying data structure is an array data structure Thread synchronization (array length is variable and 100% extended) (both querying and addition and deletion are very slow, replaced by ArrayList)

List: unique method, any method that can operate the corner mark is unique to this system

Add

boolean add(int index, E element)
boolean addAll(index,Collection)
Copy after login
 public static void List_add(){
     ArrayList a1 = new ArrayList();
     a1.add("java");
     a1.add("php");//List集合中的元素可以重复
    a1.add(".net");
     System.out.println("原集合:"+a1);
     a1.add(1, "Flash");
     a1.add(0, "ps");    
     System.out.println(a1);

    ArrayList a2 = new ArrayList();
    a2.add("javascript");
    a2.add("3dMax");
    a2.add("IBM");

    a1.addAll(0, a2);
    System.out.println(a1);
}
Copy after login

Delete the element at the specified position

 boolean remove(int index)
Copy after login
 public static void List_remove(){
     ArrayList a1 = new ArrayList();
     a1.add("javascript");
     a1.add("php");
     a1.add("flash");
     System.out.println("原集合:"+a1);

     a1.remove(0);
     System.out.println(a1);
}
Copy after login

Modify the element with the specified index set(int index, E element) Returns the modified element


 public static void List_set() {
     ArrayList a1 = new ArrayList();
     a1.add("javascript");
     a1.add("php");
     a1.add(".net");
     System.out.println("原集合:"+a1);

     a1.set(1, "falsh");
     System.out.println(a1);
}
Copy after login

Check

get(int index)   返回列表中指定位置的元素
subList(int fromIndex, int toIndex)    返回列表中指定的 fromIndex(包括 )和 toIndex(不包括)之间的部分元素。
Copy after login
 public static void List_get() {
     ArrayList a1 = new ArrayList();
     a1.add("java");
     a1.add("php");
     a1.add("flash");

     System.out.println(a1.get(0));//获取指定角标的元素,有了该方法就可以遍历该集合中的所有元素

     System.out.println(a1.subList(1, 3));//获取集合中某一部分的元素,包含头不包含尾
}
Copy after login

Unique to List collection Iterator: ListIterator (is a sub-interface of Iterator)

Note:
During iteration, you cannot operate the elements in the collection through the methods of the collection object
Because a ConcurrentModificationException (concurrency exception) will occur
So, when using the iterator , elements can only be created using the iterator method
Because the Iterator method is limited, it can only judge, remove, and delete elements
If you want other operations such as adding, modifying, etc., you need to use its sub-interface. ListIterator
This interface can only be obtained through the listIterator method of the List collection

 public class ListIteratorDemo {
     public static void main(String[] args) {
         ArrayList a1 = new ArrayList();
         a1.add("java01");
         a1.add("java02");
         a1.add("java03");
         a1.add("java04");

         System.out.println("原集合是:"+a1);

      /*在迭代过程中准备添加或者删除元素
      Iterator it = al.iterator();
      while (it.hasNext()){
        Object obj = it.next();

        if (obj.equals("java02"))
        //al.add("java008");//会出现并发异常,因为迭代器正在操作集合,不能再用集合的方法操作集合了
        it.remove();//将java02的引用从集合中删除了
        System.out.println("obj:"+obj);
        }
        */    
    //只有List的listIterator有增,删,改,查这些功能,因为只有List有索引
       ListIterator li = a1.listIterator();
          while (li.hasNext()){
          if(li.next().equals("java02"))
          //li.add("java009");
          li.set("java006");
        }   
    }
}
Copy after login

Vector: Enumeration is a unique extraction method of Vector, which is very similar to iterator (in fact, enumeration and iteration are the same) and has been replaced by iterator

 public class VectorDemo {
     public static void main(String[] args) {
         Vector v = new Vector();
         v.add("java01");
         v.add("java02");
         v.add("java03");
         v.add("java04");

         for(Enumeration en = v.elements();en.hasMoreElements();){
            System.out.println(en.nextElement());
        }
    }
}
Copy after login

LinkedList:

Special methods:

addFirst(); add elements at the head addLast(); add elements at the tail

getFirst(); getLast(); Get elements but do not delete elements. If there are no elements in the collection, NoSuchElementException will occur

removeFirst(); removeLast(); Gets the element but deletes it. If there are no elements in the collection, NoSuchElementException will occur

In JDK1.6, alternative methods

offerFirst(); offerLast();

peekFirst(); peekLast(); get the element, but the element is not deleted. If there are no elements in the collection, null will be returned

pollFirst(); pollLast(); The element is obtained, but the element is deleted. If there are no elements in the collection, null will be returned

 public class LinkedListDemo {
     public static void main(String[] args) {
         LinkedList link = new LinkedList();
         link.add("java01");
         link.add("java02");
         link.add("java03");
         link.add("java04");

         while(!link.isEmpty()){
            System.out.println((link.removeLast()));
        }
    }
}
Copy after login


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, Svelte Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, Svelte Mar 07, 2025 pm 06:09 PM

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How does Java's classloading mechanism work, including different classloaders and their delegation models? How does Java's classloading mechanism work, including different classloaders and their delegation models? Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue Fixed Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue Fixed Mar 07, 2025 pm 05:52 PM

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

Node.js 20: Key Performance Boosts and New Features Node.js 20: Key Performance Boosts and New Features Mar 07, 2025 pm 06:12 PM

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

Iceberg: The Future of Data Lake Tables Iceberg: The Future of Data Lake Tables Mar 07, 2025 pm 06:31 PM

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

How can I implement functional programming techniques in Java? How can I implement functional programming techniques in Java? Mar 11, 2025 pm 05:51 PM

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability

How to Share Data Between Steps in Cucumber How to Share Data Between Steps in Cucumber Mar 07, 2025 pm 05:55 PM

This article explores methods for sharing data between Cucumber steps, comparing scenario context, global variables, argument passing, and data structures. It emphasizes best practices for maintainability, including concise context use, descriptive

See all articles