2

In python, when you select a sublist

a = [1,2,3]
sub_a = a[2:10]

It will not blow up but return [3].

In Java, it turns out to be quite different

List<Integer> a = Arrays.asList(1,2,3);
a.subList(2, 10);

An IndexOutOfBoundsException will be thrown.

I am not going to judge the different approaches, but I want to know can Java achieve the same list slicing operation in Python's way?

1
  • 1
    Technically, the comparison is not fair. In Python, the arrays are not necessarily true arrays but dynamic arrays. Python hides this fact from you. A fair comparison would probably use ArrayList in Java, not actual true arrays. And then it is just about the slicing vs subList. Commented Apr 11, 2019 at 8:08

1 Answer 1

11

In Java you have to take care of the slicing yourself:

List<Integer> a = Arrays.asList(1,2,3);
a.subList(2, Math.min(10,a.size()));
Sign up to request clarification or add additional context in comments.

3 Comments

Or a.subList(2)
@JoopEggen is there such a variant? I don't see it (at least not in Java 8). And I checked the Javadoc of Java 11 and didn't see it.
Oh my, mixed it up with getSubstring. Sorry

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.