[Java] Java Array Linked List Class Details

This article is for learning reference only!

Related article address:

https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html

https://www.w3schools.com/java/java_arraylist.asp

https://www.runoob.com/java/java-arraylist.html

Java ArrayList Basics

ArrayList is part of the Java Collections Framework, located in the java.util package. It implements the List interface and provides dynamic resizing capabilities. Although slightly slower than standard arrays, ArrayList offers many features not found in standard arrays.

How to create ArrayList in Java

To create an ArrayList , be sure to import the java.util.ArrayList package first. Then all you need to do is call its constructor:

import java.util.ArrayList; 

ArrayList<String> guitars = new ArrayList<String>();

ArrayList supports generics, which helps enhance type safety. Programmers can create ArrayLists of any type , from simple types such as Integer , String , and Double to complex types such as HashMap or any user-defined object.

Add and remove items in ArrayList in Java

You can add values ​​to ArrayList using the **add(obj)** method which will add the object to the end of the list. Meanwhile, the add(index,obj) method adds the object at the passed index, but first moves any existing values ​​to a higher index to make room for the new object. Note that, like regular arrays, indexing is zero-based .

You can also remove values ​​from an ArrayList using remove(index) which removes the item at the given index from the list. This moves all other items in the underlying array by one ordinal position and reduces the size of the ArrayList by 1.

The following program demonstrates the add and remove methods by adding some guitars (including the guitar at a specific index) to a new ArrayList . Then delete the first item in the list:

import java.util.ArrayList; 

ArrayList<String> guitars = new ArrayList<String>();

guitars.add("Fender");
guitars.add("Gibson");
guitars.add("Jackson");
System.out.println(guitars);

// 在第二个位置插入新项目
guitars.add(1, "Washburn");
System.out.println(guitars);

// 删除第一个元素
guitars.remove(0);
System.out.println(guitars);

We can see the full program output below:

Array Lists in Java

Java ArrayList getter and setter methods

Once you have some items in the ArrayList , developers will want to access them to read or modify their values. As opposed to the square brackets ( array[index] ) used by arrays , ArrayList provides access to the underlying array through methods. You can get the object at index with obj = listName.get(index)and set the object at index with listName.set(index,obj). Here is an example of Java code based on the previous example:

// 打印列表的第三个元素
System.out.println(guitars.get(2));

guitars.set(2, "Yamaha");
// Jackson现在是Yamaha
System.out.println(guitars);

Here is the updated program output, with two new system outputs highlighted in red:

Java get and set method tutorial

How to get the size of ArrayList in Java

Unlike arrays that have a length property, ArrayList provides size()methods to get the number of items in the ArrayList . Therefore, we can get the length of the guitar by calling the method of ArrayListsize() :

guitars.set(2, "Yamaha");
// Jackson is now Yamaha
System.out.println(guitars);

// Prints 3
System.out.println(guitars.size());

Sort ArrayList in Java

For display purposes, ArrayList often needs to be sorted, which can be easily done using the **Collections.sort() or ArrayList.sort()** methods.

The Collections.sort() method is used to sort the elements of the specified list in ascending order. It is very similar to the Arrays.sort() method, but more general in that it can sort the elements of arrays as well as linked lists, queues, and many other types that extend Collections (including ArrayList ).

Remember that **Collections.sort()** mutates the original list, so you need to call it on its own line before accessing the sorted list, as in the following example:

Java Collection.sort method

Another way to sort an ArrayList is to use its own instance sort method. It differs from Collections.sort() because ArrayList 's method accepts a comparator method as an argument ( which is optional for Collections.sort() ). The comparator specifies the sort order of the ArrayList sort() and is especially useful for sorting custom objects. That being said, comparators work equally well for simple types like strings and integers :

import java.util.ArrayList;
import java.util.Comparator;

public class Main {
    
    
  public static void main(String[] args) {
    
    
    ArrayList<String> guitars = new ArrayList<>();
    guitars.add("Gibson");
    guitars.add("Yamaha");
    guitars.add("Fender");
    guitars.add("Jackson");
    
    System.out.println("guitars before sorting: " + guitars);
    
    // 使用比较器对ArrayList进行排序
    guitars.sort(new Comparator<String>() {
    
    
      @Override
      public int compare(String guitar1, String guitar2) {
    
    
        return guitar1.compareTo(guitar2);
      }
    });
    
    // 上面的sort()方法也可以使用lambda表达式编写
    guitars.sort((guitar1, guitar2) -> guitar1.compareTo(guitar2));
    
    // 一个更简洁的解决方案!
    guitars.sort(Comparator.naturalOrder());
    
    System.out.println("guitars after sorting: " + guitars);
  }
}

Using a comparator function is probably overkill for this sort of direct sort, but, as the results show, it works:

Java ArrayList sorting method

END

While plain arrays are great for holding a fixed number of values ​​of the same type, consider upgrading to ArrayList if you need to resize dynamically or think you might benefit from its many useful methods.

Guess you like

Origin blog.csdn.net/m0_47015897/article/details/131406205