2

In Java, I want to create a list based on part of an array, for example, those starting from position 2 (indexed of course from 0) to position 8, what is the convenient way of doing so without explicitly looping?

Thanks.

2
  • because there are faster and better ways? Commented Jan 8, 2012 at 5:52
  • 2
    faster? what do you think they run behind the scenes? Commented Jan 8, 2012 at 5:59

2 Answers 2

3
List<String> list = Arrays.asList(Arrays.copyOfRange(array, 2, 8));

EDIT:

To create a variable-size arraylist, use the following:

List<String> list = new ArrayList<String>(Arrays.asList(Arrays.copyOfRange(array, 2, 8)));
Sign up to request clarification or add additional context in comments.

Comments

0

Use System.arraycopy

arraycopy(source, 2, destination, 0, 7);

will copy 7 elements from source[2] through source[8] to destination[0] through destination[6].

Comments

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.