0

The Problem: I collect a unknown number of shorts into a ArrayList<Short>. When finished I need to put it into a direct ShortBuffer.

My Solution: Writing a simple loop.

But in my final Code, this will be done only once and it is not timecritical. In such a case, I always prefer a solution that needs less code.

Can it be done in a one or two liner?

Edit:

With ArrayList<Short>.toArray I can get a Short[] array, but for ShortBuffer.put() I need a short[]array. That is the problem.

testo
  • 1,052
  • 2
  • 8
  • 24

1 Answers1

1
short[] shortArray = IntStream.range(0, array.length)
    .collect(() -> new short[array.length], (b, i) -> b[i] = array[i], null);

I think will work for converting a Short[] to short[], as long as it doesn't contain null values. Or you can use apache commons lang which has the toPrimitive method do to this.

Also, When to use Array, Buffer or direct Buffer :unless there is a really special reason for using direct buffer you probably shouldn't.

Community
  • 1
  • 1
Astrogat
  • 1,617
  • 12
  • 24