Tutorial Kaedah Senarai Java - Contoh Util List API

Daftar adalah struktur data yang biasa digunakan dalam setiap bahasa pengaturcaraan.

Dalam tutorial ini kita akan menyelidiki Java List API. Kami akan memulakan operasi asas, dan kemudian kami akan memasuki perkara yang lebih maju (seperti perbandingan jenis senarai yang berbeza, seperti ArrayList dan LinkedList).

Saya juga akan memberi anda beberapa panduan untuk membantu anda memilih pelaksanaan senarai yang terbaik untuk keadaan anda.

Walaupun pengetahuan asas Java cukup untuk mengikuti tutorial, bahagian terakhir memerlukan struktur data asas (Array, LinkedList) dan pengetahuan Big-O. Sekiranya anda tidak biasa dengan perkara tersebut, sila lewati bahagian tersebut.

Definisi Senarai

Senarai disusun koleksi objek. Mereka serupa dengan urutan dalam matematik dalam erti kata itu. Namun, ia tidak seperti set, yang tidak mempunyai susunan tertentu.

Beberapa perkara yang perlu diingat: senarai dibenarkan mempunyai unsur pendua dan nol. Mereka adalah jenis rujukan atau objek, dan seperti semua objek di Jawa, mereka disimpan di timbunan.

Senarai di Java adalah antara muka dan terdapat banyak jenis senarai yang melaksanakan antara muka ini.

Saya akan menggunakan ArrayList dalam beberapa contoh pertama, kerana ia adalah jenis senarai yang paling biasa digunakan.

ArrayList pada dasarnya adalah susunan yang boleh disusun semula. Hampir selalu, anda ingin menggunakan ArrayList berbanding tatasusunan biasa kerana mereka menyediakan banyak kaedah yang berguna.

Satu-satunya kelebihan array adalah ukuran tetap mereka (dengan tidak memperuntukkan lebih banyak ruang daripada yang anda perlukan). Tetapi senarai juga menyokong ukuran tetap sekarang.

Cara Membuat Senarai di Java

Cukup berbual, mari mulakan dengan membuat senarai kami.

import java.util.ArrayList; import java.util.List; public class CreateArrayList { public static void main(String[] args) { ArrayList list0 = new ArrayList(); // Makes use of polymorphism List list = new ArrayList(); // Local variable with "var" keyword, Java 10 var list2 = new ArrayList(); } }

Dalam kurungan sudut () kita menentukan jenis objek yang akan kita simpan.

Perlu diingat bahawa jenis dalam tanda kurung mestilah jenis objek dan bukan jenis primitif . Oleh itu, kita harus menggunakan pembungkus objek, kelas Integer dan bukannya int, Double bukan pengganda, dan sebagainya.

Terdapat banyak cara untuk membuat ArrayList, tetapi saya mengemukakan tiga cara biasa dalam coretan di atas.

Cara pertama adalah dengan membuat objek dari kelas ArrayList konkrit dengan menentukan ArrayList di sebelah kiri tugasan.

Coretan kod kedua menggunakan polimorfisme dengan menggunakan senarai di sebelah kiri. Ini menjadikan tugas longgar digabungkan dengan kelas ArrayList dan membolehkan kami memberikan jenis senarai lain dan beralih ke pelaksanaan Daftar yang lain dengan mudah.

Cara ketiga adalah cara Java 10 untuk membuat pemboleh ubah tempatan dengan menggunakan kata kunci var. Penyusun menafsirkan jenis pemboleh ubah dengan memeriksa sebelah kanan.

Kita dapat melihat bahawa semua tugasan menghasilkan jenis yang sama:

System.out.println(list0.getClass()); System.out.println(list.getClass()); System.out.println(list2.getClass());

Pengeluaran:

class java.util.ArrayList class java.util.ArrayList class java.util.ArrayList 

Kami juga dapat menentukan kapasiti awal senarai.

List list = new ArrayList(20);

Ini berguna kerana setiap kali senarai penuh dan anda cuba menambahkan elemen lain, senarai semasa disalin ke senarai baru dengan kapasiti dua kali ganda dari senarai sebelumnya. Ini semua berlaku di belakang tabir.

Operasi ini menjadikan kerumitan kita O (n) , jadi kita mahu menjauhinya. Kapasiti lalai adalah 10, jadi jika anda tahu bahawa anda akan menyimpan lebih banyak elemen, anda harus menentukan kapasiti awal.

Cara Menambah dan Mengemas kini Elemen Senarai di Java

Untuk menambahkan elemen ke dalam senarai, kita boleh menggunakan kaedah tambah . Kita juga dapat menentukan indeks elemen baru, tetapi berhati-hati ketika melakukannya kerana dapat menghasilkan IndexOutOfBoundsException .

import java.util.ArrayList; public class AddElement { public static void main(String[] args) { ArrayList list = new ArrayList(); list.add("hello"); list.add(1, "world"); System.out.println(list); } }

Pengeluaran:

[hello, world]

Kita boleh menggunakan kaedah set untuk mengemas kini elemen.

list.set(1, "from the otherside"); System.out.println(list);

Pengeluaran:

[hello, world] [hello, from the otherside]

Cara Mengambil dan Menghapus Elemen Senarai di Java

Untuk mengambil elemen dari senarai, anda boleh menggunakan kaedah get dan memberikan indeks elemen yang ingin anda dapatkan.

import java.util.ArrayList; import java.util.List; public class GetElement { public static void main(String[] args) { List list = new ArrayList(); list.add("hello"); list.add("freeCodeCamp"); System.out.println(list.get(1)); } }

Pengeluaran:

freeCodeCamp 

Kerumitan operasi ini di ArrayList adalah O (1) kerana menggunakan array akses rawak biasa di latar belakang.

Untuk mengeluarkan elemen dari ArrayList, kaedah membuang digunakan.

list.remove(0);

Ini menghilangkan elemen pada indeks 0, yang "hello" dalam contoh ini.

We can also call the remove method with an element to find and remove it. Keep in mind that it only removes the first occurrence of the element if it is present.

public static void main(String[] args) { List list = new ArrayList(); list.add("hello"); list.add("freeCodeCamp"); list.add("freeCodeCamp"); list.remove("freeCodeCamp"); System.out.println(list); }

Output:

[hello, freeCodeCamp]

To remove all occurrences, we can use the removeAll method in the same way.

These methods are inside the List interface, so every List implementations has them (whether it is ArrayList, LinkedList or Vector).

How to Get the Length of a List in Java

To get the length of a list, or the number of elements,we can use the size() method.

import java.util.ArrayList; import java.util.List; public class GetSize { public static void main(String[] args) { List list = new ArrayList(); list.add("Welcome"); list.add("to my post"); System.out.println(list.size()); } } 

Output:

2

Two-Dimensional Lists in Java

It is possible to create two-dimensional lists, similar to 2D arrays.

ArrayList
    
      listOfLists = new ArrayList();
    

We use this syntax to create a list of lists, and each inner list stores integers. But we have not initialized the inner lists yet. We need to create and put them on this list ourselves:

int numberOfLists = 3; for (int i = 0; i < numberOfLists; i++) { listOfLists.add(new ArrayList()); }

I am initializing my inner lists, and I am adding 3 lists in this case. I can also add lists later if I need to.

Now we can add elements to our inner lists. To add an element, we need to get the reference to the inner list first.

For example, let's say we want to add an element to the first list. We need to get the first list, then add to it.

listOfLists.get(0).add(1);

Here is an example for you. Try to guess the output of the below code segment:

public static void main(String[] args) { ArrayList
    
      listOfLists = new ArrayList(); System.out.println(listOfLists); int numberOfLists = 3; for (int i = 0; i < numberOfLists; i++) { listOfLists.add(new ArrayList()); } System.out.println(listOfLists); listOfLists.get(0).add(1); listOfLists.get(1).add(2); listOfLists.get(2).add(0,3); System.out.println(listOfLists); }
    

Output:

[] [[], [], []] [[1], [2], [3]]

Notice that it is possible to print the lists directly (unlike with regular arrays) because they override the toString() method.

Useful Methods in Java

There are some other useful methods and shortcuts that are used frequently. In this section I want to familiarize you with some of them so you will have an easier time working with lists.

How to Create a List with Elements in Java

It is possible to create and populate the list with some elements in a single line. There are two ways to do this.

The following is the old school way:

public static void main(String[] args) { List list = Arrays.asList( "freeCodeCamp", "let's", "create"); }

You need to be cautious about one thing when using this method: Arrays.asList returns an immutable list. So if you try to add or remove elements after creating the object, you will get an UnsupportedOperationException.

You might be tempted to use final keyword to make the list immutable but it won't work as expected.

It just makes sure that the reference to the object does not change – it does not care about what is happening inside the object. So it permits inserting and removing.

final List list2 = new ArrayList(); list2.add("erinc.io is the best blog ever!"); System.out.println(list2);

Output:

[erinc.io is the best blog ever!] 

Now let's look at the modern way of doing it:

ArrayList friends = new ArrayList(List.of("Gulbike", "Sinem", "Mete")); 

The List.of method was shipped with Java 9. This method also returns an immutable list but we can pass it to the  ArrayList constructor to create a mutable list with those elements. We can add and remove elements to this list without any problems.

How to Create a List with N Copies of Some Element in Java

Java provides a method called NCopies that is especially useful for benchmarking. You can fill an array with any number of elements in a single line.

public class NCopies { public static void main(String[] args) { List list = Collections.nCopies(10, "HELLO"); System.out.println(list); } }

Output:

[HELLO, HELLO, HELLO, HELLO, HELLO, HELLO, HELLO, HELLO, HELLO, HELLO] 

How to Clone a List in Java

As previously mentioned, Lists are reference types, so the rules of passing by reference apply to them.

public static void main(String[] args) { List list1 = new ArrayList(); list1.add("Hello"); List list2 = list1; list2.add(" World"); System.out.println(list1); System.out.println(list2); }

Output:

[Hello, World] [Hello, World]

The list1 variable holds a reference to the list. When we assign it to list2 it also points to the same object. If we do not want the original list to change, we can clone the list.

ArrayList list3 = (ArrayList) list1.clone(); list3.add(" Of Java"); System.out.println(list1); System.out.println(list3);

Output:

[Hello, World] [Hello, World, Of Java]

Since we cloned list1, list3 holds a reference to its clone in this case. Therefore list1 remains unchanged.

How to Copy a List to an Array in Java

Sometimes you need to convert your list to an array to pass it into a method that accepts an array. You can use the following code to achieve that:

List list = new ArrayList(List.of(1, 2)); Integer[] toArray = list.toArray(new Integer[0]);

You need to pass an array and the toArray method returns that array after filling it with the elements of the list.

How to Sort a List in Java

To sort a list we can use Collections.sort. It sorts in ascending order by default but you can also pass a comparator to sort with custom logic.

List toBeSorted = new ArrayList(List.of(3,2,4,1,-2)); Collections.sort(toBeSorted); System.out.println(toBeSorted);

Output:

[-2, 1, 2, 3, 4]

How do I choose which list type to use?

Before finishing this article, I want to give you a brief performance comparison of different list implementations so you can choose which one is better for your use case.

We will compare ArrayList, LinkedList and Vector. All of them have their ups and downs so make sure you consider the specific context before you decide.

Java ArrayList vs LinkedList

Here is a comparison of runtimes in terms of algorithmic complexity.

| | ArrayList | LinkedList | |-----------------------|----------------------------|------------| | GET(index) | O(1) | O(n) | | GET from Start or End | O(1) | O(1) | | ADD | O(1), if list is full O(n) | O(1) | | ADD(index) | O(n) | O(1) | | Remove(index) | O(n) | O(1) | | Search and Remove | O(n) | O(n) |

Generally, the get operation is much faster on ArrayList but add and remove are faster on LinkedList.

ArrayList uses an array behind the scenes, and whenever an element is removed, array elements need to be shifted (which is an O(n) operation).

Choosing data structures is a complex task and there is no recipe that applies to every situation. Still, I will try to provide some guidelines to help you make that decision easier:

  • If you plan to do more get and add operations other than remove, use ArrayList since the get operation is too costly on LinkedList. Keep in mind that insertion is O(1) only if you call it without specifying the index and add to the end of the list.
  • If you are going to remove elements and/or insert in the middle (not at the end) frequently, you can consider switching to a LinkedList because these operations are costly on ArrayList.
  • Keep in mind that if you access the elements sequentially (with an iterator), you will not experience a performance loss with LinkedList while getting elements.

Java ArrayList vs Vector

Vector is very similar to ArrayList. If you are coming from a C++ background, you might be tempted to use a Vector, but its use case is a bit different than C++.

Vector's methods have the synchronized keyword, so Vector guarantees thread safety whereas ArrayList does not.

You might prefer Vector over ArrayList in multithreaded programming or you can use ArrayList and handle the synchronization yourself.

In a single-threaded program, it is better to stick with ArrayList because thread-safety comes with a performance cost.

Conclusion

In this post, I have tried to provide an overview of Java's List API. We have learned to use basic methods, and we've also looked at some more advanced tricks to make our lives easier.

We also made a comparison of ArrayList, LinkedList and Vector which is a commonly asked topic in interviews.

Thank you for taking the time to read the whole article and I hope it was helpful.

You can access the whole code from this repository.

If you are interested in reading more articles like this, you can subscribe to my blog's mailing list to get notified when I publish a new article.