Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

subList()

Example

Obtain a portion of a list by extracting a sublist.

import java.util.ArrayList;
public class Main {
  public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("Mazda");
   System.out.println( cars.subList(1, 3) );
  }
}

Definition and Usage

The subList() method generates a new list, referred to as a sublist, comprising the items from the original list located between specified indices.

Please be aware that the item at the last index is excluded from the sublist.

Furthermore, it’s important to note that the sublist serves as a view of the original list, implying that any modifications made to the sublist will also affect the original list.

Syntax

public List sublist(int start, int end)

Parameter Values

Parameter

Description

start

Necessary: The index indicating the beginning of the sublist.

end

Mandatory: The index marking the end of the sublist. The item at this position is not encompassed within the sublist.

Technical Details

Returns:

A fresh List comprising element from the original list.

Throws:

IndexOutOfBoundsException occurs if either index is less than zero or exceeds the list’s size.

IllegalArgumentException is thrown if the end index is smaller than the start index.

More Examples

Example

import java.util.ArrayList;
import java.util.List;
public class Main {
  public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("Mazda");
 List<String> sublist = cars.subList(1, 3);
    sublist.set(0, "Toyota");
    System.out.println(cars);
  }
}