It depends on the List implementation. Since you index arrays with ints, an ArrayList can't hold more than Integer.MAX_VALUE elements. A LinkedList isn't limited in the same way, though, and can contain any amount of elements.
Edit: I realize this sounds like an endorsement of LinkedList. But please note that although they don't have a theoretical capacity limit, linked lists are usually an inferior choice to array-based data structures because of higher memory use per element (which lowers the list's actual capacity limit) and poor cache locality (because nodes are spread all over RAM). It's definitely not the data structure you want if you have more items than can be crammed into an array.
It depends on the List implementation. Since you index arrays with ints, an ArrayList can't hold more than Integer.MAX_VALUE elements. A LinkedList isn't limited in the same way, though, and can contain any amount of elements.
Edit: I realize this sounds like an endorsement of LinkedList. But please note that although they don't have a theoretical capacity limit, linked lists are usually an inferior choice to array-based data structures because of higher memory use per element (which lowers the list's actual capacity limit) and poor cache locality (because nodes are spread all over RAM). It's definitely not the data structure you want if you have more items than can be crammed into an array.
It would depend on the implementation, but the limit is not defined by the List interface.
The interface however defines the size() method, which returns an int.
Returns the number of elements in this list. If this list contains more than
Integer.MAX_VALUEelements, returnsInteger.MAX_VALUE.
So, no limit, but after you reach Integer.MAX_VALUE, the behaviour of the list changes a bit
ArrayList (which is tagged) is backed by an array, and is limited to the size of the array - i.e. Integer.MAX_VALUE
You could try create a new list with streams. If are only 10 don't should be a performance problem create a new list.
list = list.stream().limit(10).collect(Collectors.toList());
I would look at the java.util.Collections class source and develop a SizeLimitedList similar to how they do a checkedList. Then on add I would delete the first entry from the list if the list was full.
java - What is the maximum value of index of an ArrayList? - Software Engineering Stack Exchange
java - ArrayList Limit to hold 10 Values - Stack Overflow
java - Any way to set max size of a collection? - Stack Overflow
how to set a maximum size for ArrayList? - Processing Forum
ArrayList in Java has a get(int index) method. int is a signed 32 bit value, with a maximum value of 2,147,483,647. That is the largest possible value that can be accessed in an ArrayList. Period. The specifics of what the maximum size of the array or ArrayList differe based upon the implementation of the JVM (which may be lower than the MAX_INT value). You can't make an ArrayList (or for that matter an int[] array) that has a long for its index.
If you were to try to instantiate an array list of this magnitude, you would have a structure that is at least 8 gigabytes - this only accounts for MAX_INT pointers, and not the additional space of the data at each point.
Attempting to access beyond the maximum value allowed through an iterator associated with the array would likely result in one of OutOfMemoryException, IndexOutOfBoundsException or a NoSuchElementException depending on implementation.
This is very impractical use of memory. If one was to want such a data structure, one should investigate less RAM intensive approaches such as databases, sparse arrays, and the like.
For normal arrays, if you are using the stock Oracle JVM, it seems that the actual answer is MAX_INT-5 or MAX_INT-2 depending on version.
For ArrayList the answer seems to be MAX_INT-8. (Line 191, as the source code apparently has no anchors to link to!)
In your handler method:
if(playerList.size() < 10) {
// playerList.add
} else {
// do nothing
}
Edit: Your mistake is here:
if(playerList.size() < 10) {
Button confirm = (Button) findViewById(R.id.add);
confirm.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText playername = (EditText) findViewById(R.id.userinput);
playerList.add(playername.getText().toString());
adapter.notifyDataSetChanged();
playername.setText("");
}});
} else {
// do nothing
}
You should check the size inside the onClickListener, not outside:
Button confirm = (Button) findViewById(R.id.add);
confirm.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText playername = (EditText) findViewById(R.id.userinput);
if(playerList.size() < 10) {
playerList.add(playername.getText().toString());
adapter.notifyDataSetChanged();
playername.setText("");
} else {
// do nothing
}
}
});
If you don't have control over the function that adds elements to the list, you might want to override the ArrayList add.
public class MySizeLimitedArrayList extends ArrayList<Object> {
@Override
public boolean add(Object e) {
if (this.size() < 10) {
return super.add(e);
}
return false;
}
}
You can do this:
List<X> list = Arrays.asList(new X[desiredSize]);
// where X is any Object type (including arrays and enums,
// but excluding primitives)
The resulting list is modifiable, but not resizable (i.e. add(e) and remove(e) don't work, but set(index, e) does).
Reference:
Arrays.asList(T ...)
Or: using Guava, here's a static method that decorates an existing List with a maximum size
public static <T> List<T> setMaxSize(
final List<T> input, final int maxSize){
return new ForwardingList<T>(){
@Override
public boolean addAll(Collection<? extends T> collection){
return standardAddAll(collection);
}
@Override
public boolean addAll(int index, Collection<? extends T> elements){
return standardAddAll(index, elements);
}
public boolean add(T e) {
checkMaxSize();
return delegate().add(e);
}
@Override
public void add(final int index, final T e){
checkMaxSize();
delegate().add(index, e);
}
private void checkMaxSize(){
if(size() >= maxSize){
throw new UnsupportedOperationException("Maximum Size "
+ maxSize + " reached");
}
}
@Override
protected List<T> delegate(){
return input;
}
};
}
Since ForwardingXxx classes exist for all standard collection types, you can write yourself similar decorators for other collections as well.
Obviously this will only work if your client code uses the decorated collection. If you change the underlying collection you are screwed (just like the Collections.unmodifiableXXX methods)
Reference:
ForwardingList
ArrayBlockingQueue and LinkedBlockingQueue both support a maximum size. LinkedHashMap supports eviction of the oldest or least-recently-used items when reaching a maximum size.
What do you want it to do when the maximum size is reached?
List<ViewGridObject> list2 = new ArrayList<ViewGridObject>();
for(int i=0;i<50;i++) {
try {
list2.add(list1.get(i));
} catch(Exception rr) {
list2.add(new ViewGridObject("blank","blank");
}
}
You can limit that only when you explicitly check that before you add,
or by creating a new MyArrayList where you have an ArrayLIst integrated, but in add() you do not add when size is > 15; you could return false in that case.
I suggest use the "check that before you ad"d approach:
int limit = 15;
if (list.size() < limit) {
list.add(value);
}
This should do it if memory serves:
List<MyType> fixed = Arrays.asList(new MyType[100]);
A Java list is a collection of objects ... the elements of a list. The size of the list is the number of elements in that list. If you want that size to be fixed, that means that you cannot either add or remove elements, because adding or removing elements would violate your "fixed size" constraint.
The simplest way to implement a "fixed sized" list (if that is really what you want!) is to put the elements into an array and then Arrays.asList(array) to create the list wrapper. The wrapper will allow you to do operations like get and set, but the add and remove operations will throw exceptions.
And if you want to create a fixed-sized wrapper for an existing list, then you could use the Apache commons FixedSizeList class. But note that this wrapper can't stop something else changing the size of the original list, and if that happens the wrapped list will presumably reflect those changes.
On the other hand, if you really want a list type with a fixed limit (or limits) on its size, then you'll need to create your own List class to implement this. For example, you could create a wrapper class that implements the relevant checks in the various add / addAll and remove / removeAll / retainAll operations. (And in the iterator remove methods if they are supported.)
So why doesn't the Java Collections framework implement these? Here's why I think so:
- Use-cases that need this are rare.
- The use-cases where this is needed, there are different requirements on what to do when an operation tries to break the limits; e.g. throw exception, ignore operation, discard some other element to make space.
- A list implementation with limits could be problematic for helper methods; e.g.
Collections.sort.
Integer.MAX_VALUE
or heap which ever is low will be the limit
It's very likely that you will run out of heap space well before you get anywhere close to Integer.MAX_VALUE number of elements, but let's see what would happen if we had infinite memory and tried to add more than Integer.MAX_VALUE elements to a List:
1) ArrayList:
An ArrayList will try to increase its capacity:
int newCapacity = (oldCapacity * 3)/2 + 1;
This calculation will overflow and newCapacity will actually be less than Integer.MAX_VALUE. The ArrayList will then try to copy the elements in the original array to a smaller array and will hence lose elements.
2) LinkedList:
A LinkedList works a bit better once you cross the Integer.MAX_VALUE limit. It will continue to hold elements, however the size attribute will suffer from integer overflow and will affect other operations that make use of it.