Susunan di Jawa: Panduan Rujukan

1. Pengenalan

Dalam tutorial ini, kita akan menyelami konsep teras dalam bahasa Java - array.

Kami pertama kali akan melihat apa itu array, kemudian bagaimana menggunakannya; secara keseluruhan, kami akan merangkumi cara:

  • Mulakan dengan tatasusunan
  • Membaca dan menulis unsur tatasusila
  • Gelung pada array
  • Ubah susunan menjadi objek lain seperti Senarai atau Aliran
  • Susun, cari dan gabungkan tatasusunan

2. Apakah Array?

Perkara pertama yang pertama, kita perlu menentukan apa itu array? Menurut dokumentasi Java, array adalah objek yang berisi sejumlah nilai tetap dari jenis yang sama . Unsur-unsur array diindeks, yang bermaksud kita dapat mengaksesnya dengan angka (disebut indeks ).

Kita boleh menganggap array sebagai senarai sel bernombor, setiap sel menjadi pemboleh ubah yang memegang nilai. Di Jawa, penomboran bermula pada 0.

Terdapat susunan jenis primitif dan susunan jenis objek. Ini bermaksud kita dapat menggunakan tatasusunan int, float, boolean,… Tetapi juga array String, Object dan jenis custom juga.

3. Menyiapkan Array

Sekarang tatasusila ditentukan dengan baik, mari kita selami penggunaannya.

Kami akan merangkumi banyak topik yang mengajar kami cara menggunakan tatasusunan. Kami akan mempelajari beberapa asas seperti cara menyatakan dan memulakan array, tetapi kami juga akan merangkumi subjek yang lebih maju seperti menyusun dan mencari tatasusunan.

Mari kita pergi dahulu dengan pengisytiharan dan inisialisasi.

3.1. Pengisytiharan

Kita akan mulakan dengan pengisytiharan. Terdapat dua cara untuk menyatakan array di Java:

int[] anArray;

atau:

int anOtherArray[];

Yang pertama lebih banyak digunakan daripada yang terakhir .

3.2. Permulaan

Sekarang sudah tiba masanya untuk melihat bagaimana memulakan array. Sekali lagi terdapat pelbagai cara untuk memulakan array. Kami akan melihat yang utama di sini, tetapi artikel ini merangkumi permulaan array secara terperinci.

Mari mulakan dengan cara mudah:

int[] anArray = new int[10];

Dengan menggunakan kaedah ini, kami menginisialisasi susunan sepuluh elemen int . Perhatikan bahawa kita perlu menentukan ukuran array.

Semasa menggunakan kaedah ini, kami menginisialisasi setiap elemen ke nilai lalai , di sini 0 . Semasa memulakan array Objek , unsur-unsur adalah nol secara lalai.

Kita sekarang akan melihat cara lain yang memberi kita kemungkinan untuk menetapkan nilai pada array secara langsung semasa membuatnya:

int[] anArray = new int[] {1, 2, 3, 4, 5};

Di sini, kami menginisialisasi susunan lima elemen yang mengandungi nombor 1 hingga 5. Apabila menggunakan kaedah ini, kita tidak perlu menentukan panjang array, itu adalah jumlah elemen yang kemudian dinyatakan antara pendakap.

4. Mengakses Elemen

Sekarang mari kita lihat cara mengakses elemen array. Kita dapat mencapainya dengan memerlukan kedudukan sel array.

Contohnya, coretan kod kecil ini akan mencetak 10 ke konsol:

anArray[0] = 10; System.out.println(anArray[0]);

Perhatikan bagaimana kita menggunakan indeks untuk mengakses sel array. Nombor antara tanda kurung adalah kedudukan spesifik array yang ingin kita akses.

Ketika mengakses sel, jika indeks lulus negatif atau melampaui sel terakhir, Java akan membuang ArrayIndexOutOfBoundException .

Kita harus berhati-hati agar tidak menggunakan indeks negatif, atau indeks yang lebih besar dari atau sama dengan ukuran array .

5. Berterusan di Atas Array

Mengakses elemen satu demi satu boleh berguna, tetapi kita mungkin mahu melakukan lelaran melalui array. Mari lihat bagaimana kita dapat mencapainya.

Cara pertama adalah menggunakan gelung untuk :

int[] anArray = new int[] {1, 2, 3, 4, 5}; for (int i = 0; i < anArray.length; i++) { System.out.println(anArray[i]); }

Ini mesti mencetak nombor 1 hingga 5 ke konsol. Seperti yang kita lihat, kita menggunakan harta panjang . Ini adalah harta awam yang memberi kita ukuran susunan.

Sudah tentu, mungkin menggunakan mekanisme gelung lain seperti ketika atau buat sementara waktu . Tetapi, untuk koleksi Java, mungkin untuk melengkapkan array menggunakan gelung foreach :

int[] anArray = new int[] {1, 2, 3, 4, 5}; for (int element : anArray) { System.out.println(element); }

This example is equivalent to the previous one, but we got rid of the indices boilerplate code. The foreach loop is an option when:

  • we don't need to modify the array (putting another value in an element won't modify the element in the array)
  • we don't need the indices to do something else

6. Varargs

We've already covered the basics when it comes to the creation and manipulation of arrays. Now, we'll dive into more advanced topics, beginning with varargs. As a reminder, varargs are used to pass an arbitrary number of arguments to a method:

void varargsMethod(String... varargs) {}

This method could take from 0 to an arbitrary number of String arguments. An article covering varargs can be found here.

What we have to know here is that inside the method body, a varargs parameter turns into an array. But, we can also pass an array directly as the argument. Let's see how by reusing the example method declared above:

String[] anArray = new String[] {"Milk", "Tomato", "Chips"}; varargsMethod(anArray);

Will behave the same as:

varargsMethod("Milk", "Tomato", "Chips");

7. Transforming an Array into a List

Arrays are great, but sometimes it can be handier to deal with List instead. We'll see here how to transform an array into a List.

We'll first do it the naïve way, by creating an empty list and iterating over the array to add its elements to the list:

int[] anArray = new int[] {1, 2, 3, 4, 5}; List aList = new ArrayList(); for (int element : anArray) { aList.add(element); }

But there is another way, a little bit more succinct:

Integer[] anArray = new Integer[] {1, 2, 3, 4, 5}; List aList = Arrays.asList(anArray);

The static method Arrays.asList takes a varargs argument and creates a list with the passed values. Unfortunately, this method comes with some drawbacks:

  • It's not possible to use an array of primitive types
  • We can't add or remove elements from the created list, as it'll throw an UnsupportedOperationException

8. From an Array to a Stream

We can now transform arrays into lists, but since Java 8 we have access to the Stream API and we might want to turn our arrays into Stream. Java provides us with the Arrays.stream method for that:

String[] anArray = new String[] {"Milk", "Tomato", "Chips"}; Stream aStream = Arrays.stream(anArray);

When passing an Object array to the method it will return a Stream of the matching type (e.g. Stream for an array of Integer). When passing a primitive one it will return the corresponding primitive Stream.

It's also possible to create the stream only on a subset of the array:

Stream anotherStream = Arrays.stream(anArray, 1, 3);

This will create a Stream with only “Tomato” and “Chips” Strings (the first index being inclusive while the second one is exclusive).

9. Sorting Arrays

Let's now see how to sort an array, that is rearranging its elements in a certain order. The Arrays class provides us with the sort method. A bit like the stream method, sort has a lot of overloadings.

There are overloadings to sort:

  • Primitive type arrays: which are sorted in ascending order
  • Object arrays (those Object must implement the Comparable interface): which are sorted according to the natural order (relying on the compareTo method from Comparable)
  • Generic arrays: which are sorted according to a given Comparator

In addition, it's possible to sort only a specific portion of an array (passing start and end indices to the method).

The algorithms behind the sort method are quick sort and merge sort for primitive and other arrays, respectively.

Let's see how this all work through some examples:

int[] anArray = new int[] {5, 2, 1, 4, 8}; Arrays.sort(anArray); // anArray is now {1, 2, 4, 5, 8} Integer[] anotherArray = new Integer[] {5, 2, 1, 4, 8}; Arrays.sort(anotherArray); // anotherArray is now {1, 2, 4, 5, 8} String[] yetAnotherArray = new String[] {"A", "E", "Z", "B", "C"}; Arrays.sort(yetAnotherArray, 1, 3, Comparator.comparing(String::toString).reversed()); // yetAnotherArray is now {"A", "Z", "E", "B", "C"}

10. Searching in an Array

Searching an array is pretty simple, we can loop over the array and search our element among the array elements:

int[] anArray = new int[] {5, 2, 1, 4, 8}; for (int i = 0; i < anArray.length; i++) { if (anArray[i] == 4) { System.out.println("Found at index " + i); break; } }

Here we searched for number 4 and found it at index 3.

If we have a sorted array though, we can use another solution: the binary search. The principle of binary search is explained in this article.

Fortunately, Java provides us with the Arrays.binarySearch method. We have to give it an array and an element to search.

In case of a generic array, we also have to give it the Comparator that was used to sort the array in the first place. There is again the possibility to call the method on a subset of the array.

Let's see an example of the binary search method usage:

int[] anArray = new int[] {1, 2, 3, 4, 5}; int index = Arrays.binarySearch(anArray, 4); System.out.println("Found at index " + index);

As we stored number 4 in the fourth cell, this will return index 3 as the result. Note that we used an already sorted array.

11. Concatenating Arrays

Finally, let's see how to concatenate two arrays. The idea is to create an array which length is the sum of the two arrays to concatenate. After that we have to add the elements of the first one and then the elements of the second one:

int[] anArray = new int[] {5, 2, 1, 4, 8}; int[] anotherArray = new int[] {10, 4, 9, 11, 2}; int[] resultArray = new int[anArray.length + anotherArray.length]; for (int i = 0; i < resultArray.length; i++) { resultArray[i] = (i < anArray.length ? anArray[i] : anotherArray[i - anArray.length]); }

As we can see, when the index is still lesser than the first array length we add elements from that array. Then we add elements from the second one. We can make use of the Arrays.setAll method to avoid writing a loop:

int[] anArray = new int[] {5, 2, 1, 4, 8}; int[] anotherArray = new int[] {10, 4, 9, 11, 2}; int[] resultArray = new int[anArray.length + anotherArray.length]; Arrays.setAll(resultArray, i -> (i < anArray.length ? anArray[i] : anotherArray[i - anArray.length]));

This method will set all array element according to the given function. This function associates an index with a result.

Berikut adalah pilihan ketiga untuk bergabung ke tatasusunan: System.arraycopy . Kaedah ini mengambil susunan sumber , kedudukan sumber, susunan tujuan , kedudukan tujuan dan int yang menentukan bilangan elemen untuk disalin:

System.arraycopy(anArray, 0, resultArray, 0, anArray.length); System.arraycopy(anotherArray, 0, resultArray, anArray.length, anotherArray.length);

Seperti yang dapat kita lihat, kita menyalin susunan pertama, kemudian yang kedua (selepas unsur terakhir yang pertama).

12. Kesimpulannya

Dalam artikel terperinci ini kami telah membahas penggunaan asas dan beberapa susunan laras di Java.

Kami melihat bahawa Java menawarkan banyak kaedah untuk menangani array melalui kelas utiliti Arrays . Terdapat juga kelas utiliti untuk memanipulasi tatasusunan di perpustakaan seperti Apache Commons atau Guava.

Kod penuh untuk artikel ini boleh didapati di GitHub kami.