subList() yöntemi nedir?
Koleksiyonlar Çerçevesi, Java API'sinde çok popüler bir bileşendir. Liste arabirimi ve ArrayList sınıfı, Collections Framework'teki muhtemelen en önemli araçlardır. subList , Liste arabiriminde var olan bir listenin bir bölümünden yeni bir liste oluşturmanıza izin veren bir yöntemdir. Ancak, bu yeni oluşturulan liste yalnızca orijinal listeye referans veren bir görünümdür.
Bir ArrayList nesnesindeki subList yöntemi örneği.
Ülkelerin ArrayList'ini ilan ediyoruz. Ardından 2. ve 4. elementler arasındaki kısmı döndürmeye çalışıyoruz.
import java.util.*;
public class Main {
public static void main(String[] args) {
// create an ArrayList
ArrayList list = new ArrayList();
// add values to ArrayList
list.add("USA");
list.add("UK");
list.add("France");
list.add("Germany");
list.add("Russia");
System.out.println("List of the countries:" + list);
//Return the subList : 1 inclusive and 3 exclusive
ArrayList new_list = new ArrayList(list.subList(1, 3));
System.out.println("The subList of the list: "+new_list);
}
}
Yukarıdaki kodun çıktısı şöyle olacaktır:
Ülkelerin listesi:[ABD, İngiltere, Fransa, Almanya, Rusya] Listenin alt listesi: [İngiltere, Fransa]
Bir ArrayList'te birinci elemanın indeks değeri 0'dır. Bu nedenle ikinci ve dördüncü elemanın indeks değerleri sırasıyla 1 ve 3'tür. Bu nedenle, sublist() yöntemini list.subList(1, 3) olarak çağırıyoruz . Ancak, subList yönteminin bu durumda dördüncü öğe olan (“Almanya”) toIndex dışındaki kısmı döndürdüğünü unutmayın . Böylece yalnızca "İngiltere" ve "Fransa" çıktısını alacaktır . Döndürülen çıktı bir List olduğundan, herhangi bir List yöntemini doğrudan onun üzerinde çağırabilirsiniz. Peki her iki parametre için de aynı indeksi kullanırsak ne olur? Bu dizin, döndürülen listeye dahil edilecek mi yoksa hariç tutulacak mı? Hadi bulalım.
//execute subList() method with the same argument for both parameters.
ArrayList new_list2 = new ArrayList(list.subList(3, 3));
System.out.println("The subList of the list: "+new_list2);
Çıktı
Listenin alt listesi: [ ]
Çıktı boş bir listedir. fromIndex 4. öğeyi seçse bile, aynı zamanda toIndex olduğu için subList() yöntemi onu kaldıracaktır.
Bir LinkedList nesnesindeki subList yöntemi örneği.
Bu örnekte, bir LinkedList öğesinde alt liste yöntemini kullanacağız. Yine, belirtilen index fromIndex(include) ve toIndex(exclusive) arasındaki listeyi döndürür . subList() yöntemi tarafından döndürülen listenin yalnızca orijinal listeye referansı olan bir görünüm olduğunu söylediğimizi unutmayın. Alt listede herhangi bir değişiklik yaparsanız orijinal listeyi de etkiler. Bunu da bu örnekte test edeceğiz.
import java.util.LinkedList;
import java.util.Iterator;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Create a LinkedList
LinkedList linkedlist = new LinkedList();
// Add elements to LinkedList
for(int i = 0; i<7; i++){
linkedlist.add("Node "+ (i+1));
}
// Displaying LinkedList elements
System.out.println("Elements of the LinkedList:");
Iterator it= linkedlist.iterator();
while(it.hasNext()){
System.out.print(it.next()+ " ");
}
// invoke subList() method on the linkedList
List sublist = linkedlist.subList(2,5);
// Displaying SubList elements
System.out.println("\nElements of the sublist:");
Iterator subit= sublist.iterator();
while(subit.hasNext()){
System.out.print(subit.next()+" ");
}
/* The changes you made to the sublist will affect the original LinkedList
* Let’s take this example - We
* will remove the element "Node 4" from the sublist.
* Then we will print the original LinkedList.
* Node 4 will not be in the original LinkedList too.
*/
sublist.remove("Node 4");
System.out.println("\nElements of the LinkedList LinkedList After removing Node 4:");
Iterator it2= linkedlist.iterator();
while(it2.hasNext()){
System.out.print(it2.next()+" ");
}
}
}
Çıktı şöyle görünecektir:
LinkedList'in Öğeleri: Düğüm 1 Düğüm 2 Düğüm 3 Düğüm 4 Düğüm 5 Düğüm 6 Düğüm 7 Alt listenin öğeleri: Düğüm 3 Düğüm 4 Düğüm 5 LinkedList'in Öğeleri LinkedList Düğüm 4'ü kaldırdıktan sonra: Düğüm 1 Düğüm 2 Düğüm 3 Düğüm 5 Düğüm 6 düğüm 7
Dizinler subList() içinde sınır dışına çıkarsa ne olur?
subList yöntemi iki tür istisna döndürür . Onlara bir göz atalım. Belirtilen dizinlerin List öğesinin (fromIndex < 0 || toIndex > size) aralığı dışında olduğu bir durumu göz önünde bulundurun . Sonra bir IndexOutOfBoundExecption atar .
//using subList() method with fromIndex <0
ArrayList new_list2 = new ArrayList(list.subList(-1, 3));
System.out.println("Portion of the list: "+new_list2);
Exception in thread "main" java.lang.IndexOutOfBoundsException: fromIndex = -1
// using subList() method with toIndex > size
ArrayList new_list2 = new ArrayList(list.subList(3, 6));
System.out.println("Portion of the list: "+new_list2);
Exception in thread "main" java.lang.IndexOutOfBoundsException: toIndex = 6
Ayrıca, fromIndex, toIndex (fromIndex > toIndex) değerinden büyükse , subList() yöntemi bir IllegalArgumentException hatası atar .
//If fromIndex > toIndex
ArrayList new_list2 = new ArrayList(list.subList(5, 3));
System.out.println("Portion of the list: "+new_list2);
Exception in thread "main" java.lang.IllegalArgumentException: fromIndex(5) > toIndex(3)
Çözüm
Bu yazıda subList yöntemini ve nasıl kullanılacağını ele aldık. subList() yöntemi, açık aralık işlemlerine olan ihtiyacı ortadan kaldırır (Genellikle diziler için var olan bir işlem türüdür). Unutulmaması gereken en önemli şey, subList yönteminin yeni bir örnek değil, orijinal listeye referansı olan bir görünüm döndürmesidir. Bu nedenle, aynı listede subList yönteminin aşırı kullanılması, Java uygulamanızda bir iş parçacığının takılmasına neden olabilir.
Daha fazla okuma: |
---|
GO TO FULL VERSION