1

So I modified an API (for command management) to use String[] instead of a list of Strings.

My problem is here:strings.subList(1, strings.length) So I need to change this to a different alternative that would do the same job.

What exactly could I do here?

Erik
  • 31
  • 4
  • I can't read that code. Could you please reformat it? – Sam Estep Jun 28 '15 at 11:49
  • (The proposed duplicate wasn't a duplicate, IMO - this is explicitly looking for an equivalent of subList, which provides a *view* of part of an list.) – Jon Skeet Jun 28 '15 at 11:54
  • @JonSkeet: Perhaps I'm just misinterpreting the question; to me it sounds like the OP wants to rewrite his code from Lists to arrays, but can't figure out an equivalent to subList. (But agree that copyOfRange, etc. won't provide a view...) – Oliver Charlesworth Jun 28 '15 at 11:55
  • @OliverCharlesworth: Yes, but at least the *answers* to the question you marked as a duplicate were all not equivalent to subList, as they were creating copies. I agree the questions sound similar, but with the explicit use of `subList` in this question, I think they're different enough to both stand separately. – Jon Skeet Jun 28 '15 at 11:57

2 Answers2

2

You can't get one array which is a sliced view of another - but you can make a list view over an array, and then use sublist on that:

List<String> stringList = Arrays.asList(strings);
List<String> subList = stringList.subList(1, strings.length);

Now you won't be able to pass that to anything taking an array, of course...

So your options are:

  • Go back to using a List<String> everywhere - this would be my suggestion, as collection classes are generally more flexible than arrays
  • Use arrays for part of the code, but collection classes elsewhere
  • Copy part of the array instead (e.g. using System.arraycopy or Arrays.copyOfRange)
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

If you're looking to copy just part of an array into a new array, I would advise that you use the Arrays.copyOfRange function:

Arrays.copyOfRange(strings, 1, strings.length());

(sees Jon Skeet's answer, skitters away sheepishly)

Sam Estep
  • 12,974
  • 2
  • 37
  • 75