How to get a sub array of array in Java, without copying data?

Viewed 80481

I have some library of classes, working with my data, which is being read into buffer. Is it possible somehow to avoid copying arrays again and again, passing parts of data deeper and deeper into processing methods? Well, it sounds strange, but in my particular case, there's a special writer, which divides data into blocks and writes them individually into different locations, so it just performs System.arraycopy, gets what it needs and calls underlying writer, with that new sub array. And this happens many times. What is the best approach to refactor such code?

9 Answers

You could use (ArrayList).subList(value1, value2) i belive, perhaps that could help in your case? That is ofcourse if you want to use an ArrayList.

Perhaps instead of working with arrays you should work with a different type that maintains a reference to a slice of the original array, instead of copying the data over, similar to ArraySegment in C#. An additional benefit to this is that you can also shift the slice over the original array on-demand, without creating new instances. Pseudo code:

public class ArraySegment<T> implements Iterable<T> 
{
      private int from, to;
      private T[] original;
      
      public ArraySegment<T>(T[] original, int from, int to)
      {
          //constructor stuff
      }

      public T get(int index)
      {
           return original[index + from];
      }

      public int size()
      {
          return to - from + 1;
      }
      
      @Override
      public Iterator<T> iterator()
      {
          //Iterator that iterates over the slice
      }

      //Can support setters on from/to variables
}

Google's Guava libraries support the slice concept in the form of a ByteSource.

Google Guava is a readily available open-source package of functionality, written from the ground up to follow Google best practices, which depend on significant array slicing capabilities.

Related