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

前端 未结 9 1878
执念已碎
执念已碎 2020-12-28 11:58

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

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-28 12:23

    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 implements Iterable 
    {
          private int from, to;
          private T[] original;
          
          public ArraySegment(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 iterator()
          {
              //Iterator that iterates over the slice
          }
    
          //Can support setters on from/to variables
    }
    

提交回复
热议问题