Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum Size List in Java

It's useful to me to have a data structure in Java that has all the functionality of a List, but has a maximum storage capacity, and drops older data when newer data is added. Conceivably at some point I might want to implement a fixed size Queue which keeps a more general ordering of the data, and drops the old data lowest in that ordering, but that's the for the future.

At the moment I'm implementing it like this:

public class FixedSizeList<T> {

  private final int maxSize;
  private final LinkedList<T> list = new LinkedList<T>();

  public FixedSizeQueue(int maxSize) {
    this.maxSize = maxSize < 0 ? 0 : maxSize;
  }

  public T add(T t) {
    list.add(t);
    return list.size() > maxSize ? list.remove() : null;
  }

  // add remaining methods...

}

Is there either (a) an existing data structure that serves my needs, or (b) a better way of implementing this data structure?

like image 793
Chris Taylor Avatar asked May 17 '11 08:05

Chris Taylor


People also ask

What is the maximum size of an ArrayList?

The theoretical limit for ArrayList capacity is Integer. MAX_VALUE, a.k.a. 2^31 - 1, a.k.a. 2,147,483,647.

What is size of list in Java?

The size() method of the List interface in Java is used to get the number of elements in this list. That is, this method returns the count of elements present in this list container. Parameters: This method does not take any parameters. Return Value: This method returns the number of elements in this list.

How many elements can a list hold in Java?

A Java program can only allocate an array up to a certain size. It generally depends on the JVM that we're using and the platform. Since the index of the array is int, the approximate index value can be 2^31 – 1. Based on this approximation, we can say that the array can theoretically hold 2,147,483,647 elements.

How many objects can an ArrayList hold?

Since ArrayList in Java is backed by a built-in array, the limit on the size is equal the same as the limit on the size of an array, i.e. 2147483647. Since your project is for android platform, you would run out of memory before reaching this limit. However, 8000 is a relatively small number.


1 Answers

I would use array and 2 indexes for head and tail of the list.Make sure that head is always < tail and you're safe.

like image 73
jdevelop Avatar answered Oct 20 '22 22:10

jdevelop