CodeGym /Java Blog /무작위의 /Java의 Sublist() 메서드: ArrayList 및 List
John Squirrels
레벨 41
San Francisco

Java의 Sublist() 메서드: ArrayList 및 List

무작위의 그룹에 게시되었습니다

subList() 메서드는 무엇입니까?

컬렉션 프레임워크는 Java API에서 매우 인기 있는 구성 요소입니다. List 인터페이스와 ArrayList 클래스는 아마도 Collections Framework에서 가장 중요한 도구일 것입니다. subList 는 기존 목록의 일부에서 새 목록을 만들 수 있는 List 인터페이스의 메서드입니다. 그러나 새로 생성된 이 목록은 원래 목록을 참조하는 보기일 뿐입니다. Java의 Sublist() 메서드: ArrayList 및 List - 1예를 들어 [1,2,3,4,5,6] 목록을 가져옵니다. 첫 번째 요소와 마지막 요소 없이 새 목록을 만들고 싶다고 가정합니다. 이러한 시나리오에서는 list.subList() 메서드가 도움이 될 것입니다. subList(fromIndex, toIndex) 메서드는 하나의 형식만 가지며 첫 번째 인덱스 (fromIndex) 와 마지막 인덱스 인 두 개의 인수를 취합니다.(toIndex) . fromIndex toIndex 사이의 부분을 새 목록으로반환합니다기억해야 할 중요한 점이 있습니다. 새로 생성된 목록에는 fromIndex가 포함되고 toIndex는 제외됩니다. 따라서 위 시나리오의 알고리즘은 다음과 같습니다. List = [1,2,3,4,5,6] newList = List.subList(1,5) subList 는 List 인터페이스의 메서드이므로 ArrayList, LinkedList, Stack, Vector 객체에 사용할 수 있습니다. 그러나 이 기사에서는 주로 ArrayList 및 LinkedList 객체에 중점을 둘 것입니다.

ArrayList 객체에 대한 subList 메서드의 예.

우리는 국가의 ArrayList를 선언하고 있습니다. 그런 다음 두 번째 요소와 네 번째 요소 사이의 부분을 반환하려고 합니다.

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);
    }
 }
위 코드의 출력은
국가 목록:[미국, 영국, 프랑스, ​​독일, 러시아] 목록 하위 목록: [영국, 프랑스]
ArrayList에서 첫 번째 요소의 인덱스 값은 0입니다. 따라서 두 번째 및 네 번째 요소의 인덱스 값은 각각 1과 3입니다. 따라서 sublist() 메서드를 list.subList(1, 3) 로 호출합니다 . 단, 이 경우 subList 메서드는 4번째 요소 ("Germany") 인 toIndex를 제외한 부분을 반환한다는 점을 기억하자 . 따라서 "UK""France" 만 출력합니다 . 반환된 출력은 List 자체이므로 List 메서드에서 직접 호출할 수 있습니다. 두 매개변수에 동일한 인덱스를 사용하면 어떻게 될까요? 해당 인덱스가 반환된 목록에 포함되거나 제외됩니까? 알아 보자.

//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);
출력은
목록의 하위 목록: [ ]
출력은 빈 목록입니다. fromIndex가 4번째 요소를 선택하더라도 subList() 메서드는 toIndex이기도 하므로 이를 제거합니다.

LinkedList 개체에 대한 subList 메서드의 예입니다.

이 예제에서는 LinkedList 요소에 하위 목록 메서드를 사용합니다. 다시, 지정된 인덱스 fromIndex(inclusive)toIndex(exclusive) 사이의 목록을 반환합니다 . subList() 메서드 에 의해 반환된 목록은 원래 목록에 대한 참조가 있는 보기일 뿐이라고 말한 것을 기억하십시오. 하위 목록을 변경하면 원래 목록에도 영향을 미칩니다. 이 예제에서도 테스트할 것입니다.

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()+" ");
    }
 }
}
출력은 다음과 같습니다.
LinkedList의 요소: Node 1 Node 2 Node 3 Node 4 Node 5 Node 6 Node 7 하위 목록의 요소: Node 3 Node 4 Node 5 LinkedList의 요소 LinkedList Node 4 제거 후: Node 1 Node 2 Node 3 Node 5 Node 6 노드 7

인덱스가 subList()에서 범위를 벗어나면 어떻게 됩니까?

subList 메서드 두 가지 유형의 예외를 반환합니다. 그것들을 살펴봅시다. 지정된 인덱스가 List 요소의 범위를 벗어난 경우 (fromIndex < 0 || toIndex > size) 상황을 고려하십시오 . 그런 다음 IndexOutOfBoundExecption 이 발생합니다 .

//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
또한 fromIndex가 toIndex보다 큰 경우 (fromIndex > toIndex) subList () 메서드는 IllegalArgumentException 오류를 발생시킵니다.

//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)

결론

이 기사에서는 subList 메서드와 사용 방법에 대해 설명했습니다. subList() 메서드를 사용하면 명시적인 범위 작업이 필요하지 않습니다(배열에 일반적으로 존재하는 작업 유형임). 기억해야 할 가장 중요한 사항은 subList 메서드가 새 인스턴스를 반환하지 않고 원래 목록에 대한 참조가 있는 보기를 반환한다는 것입니다. 따라서 동일한 목록에서 subList 메소드를 과도하게 사용하면 Java 애플리케이션에서 스레드가 멈출 수 있습니다.
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION