initiate the ArrayList with maximum size - java

Is it possible in initiate the ArrayList with fixed size so it may not increase more than that and initiate all the initial occupancy to 0? in actual forcing it to behave like an ordinary Array so we can use the add() upto to the array size.

Why not use normal array rather than ArrayList
ArrayList are basically simply an array with support for the situation where we may have to add more items. If we're not changing the size of that ArrayList than it's just like the conventional array

You can use
List<Integer> list = Arrays.asList(new Integer[desiredLength]);
to produce a fixed size List<Integer> in which all the elements are initialized to null. Then you can use list.set(index,value) to modify elements of that List. You can't use add though, since add changes the size of the List, which is not allowed in fixed sized lists.
If you want to initialize the List to non-null values, you can do something like this :
Integer[] arr = new Integer[desiredLength];
Arrays.fill(arr,0);
List<Integer> list = Arrays.asList(arr);

You can, by using only arraylist, ensure a minimum size of the arraylist:
ArrayList<T> myArrayList = new ArrayList();
myArrayList.ensureCapacity(n);
But that doesn't set a fixed size, just something bigger than n, and it doesn't prevent you to add more than n.
As mentioned by other, you are probably better off doing something else. If you really want to achieve that, you can write your own collection:
public class MyArrayList<T> {
ArrayList<T> arrayList;
int size;
public MyArrayList(int size) {
this.size = size;
arrayList = new ArrayList<>();
arrayList.ensureCapacity(size);
}
public void add(T x) {
if (arrayList.size() >= size) {
throw new IllegalStateException();
}
arrayList.add(x);
}
//remove, etc.. . You can even extend/implement arrayList/list if you want to do polymorphism.
}

Related

Length of ArrayList in Java

How do I find the size of an ArrayList in Java? I do not mean the number of elements, but the number of indexes.
public static void main(String[] args) {
ArrayList hash = new ArrayList(5);
System.out.println(hash.size());
}
Prints out "0." Using:
System.out.println(hash.toArray().length);
Also prints out a "0."
I have looked in http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html but I do not see a method that will help me. Is my ArrayList reverting to a size of 0 if I do not add anything to it?
EDIT The assignment is to create a hash table using ArrayList. I am supposed to create a hash function using the formula
double hashkey = Math.floor(hash.size()*(Math.E*key-Math.floor(Math.E*key)));
Where key is an integer. hashkey then becomes the index where the value will be stored. I am using hash.size() as a placeholder at the moment, but that value should be the capacity of my ArrayList.
ArrayList.size() will give the current size.That's why hash.size() giving you the current size of your ArrayList hash. It will not give you the capacity.
You just initialized the list. Have not add any elements to your arraylist, that's why its giving 0.
There is no such method in the ArrayList API. The capacity of an ArrayList is hidden by design.
However, I think that your question is based on a misunderstanding.
How do I find the size of an ArrayList in Java? I do not mean the number of elements, but the number of indexes.
In fact, the size of a List, the number of elements in a List, and the number of indexes (i.e. indexable positions) for a List ... are all the same thing.
The capacity of an ArrayList is something different. It is the number of elements that the object could contain, without reallocating the list's backing array. However, the fact that the list has a capacity N does NOT mean that you can index up to N - 1. In fact, you can only index up to size() - 1, irrespective of the capacity.
Now to deal with your examples:
ArrayList list = new ArrayList(5);
System.out.println(list.size());
This prints out zero because the list has zero elements. The ArrayList() and ArrayList(int) constructors both create and return lists that are empty. The list currently has space for 5 elements (because you gave it an initial capacity of 5) but you can't index those slots.
System.out.println(list.toArray().length);
This prints zero because when you copy the list's contents to an array (using toArray()), the array is the same size as the list. By definition.
This does not mean that the list's backing array has changed. On the contrary, it is still big enough to hold 5 elements without reallocation ... just like before.
But ... I hear you say ... the array's length is zero!
Yes, but that is not the backing array! The toArray() method allocates a new array and copies the List contents into that array. It does NOT return the actual backing array.
Maybe you should encapsulate your ArrayList in a class and add another attribute private int capacity in that class as well.
public class AdvancedArrayList<T>
{
private int capacity;
private ArrayList<T> list;
public AdvancedArrayList<T>(int capacity)
{
this.capacity = capacity;
list = new ArrayList<>();
}
public ArrayList<T> getList()
{
return list;
}
public int getCapacity()
{
return capacity;
}
public void addElement(T element)
{
if(list.size() < capacity)
list.add(element);
else
System.out.println("Capacity is full");
}
}
Notice that size is different than capacity.

Initializing class object

I am new to Java. I apologize if I ask a simple thing.
I wrote the below code but it seems that it doesn't initialize properly. because when I print the size of list1 it show the size = 0!! However, it should be 4!
public static class MyClass{
public List <Integer> list1
// Class Constructor
public MyClass(int n){
list1 = new ArrayList <Integer> (n);
System.out.println("Size = " + list1.size() );
// prints Size = 0 !!!why???
}
public void init(int n){
for(int cnt1 = 0; cnt1 < list1.size(); cnt1++){
list1.set(cnt1 , cnt1);
}
}
...}
public static List<Integer> Func1(int n){
MyClass = new myclass (n);
myclass.init(n);
... }
public static void main(String args[]){
int n = 4;
result = Func1 (n);
...}
Why the size of the list1 is 0? It should be 4, because I pass 4 to Func1, and then it creates MyClass object with size n.
I would be thankful if someone can help me about this problem.
Array lists in Java have both a size and a capacity.
Size tells you how many items are there in the list, while
Capacity tells you how many items the list can hold before it needs to resize.
When you call ArrayList(int) constructor, you set the capacity, not the size, of the newly created array list. That is why you see zero printed out when you get the size.
Having a capacity of 4 means that you can add four integers to the list without triggering a resize, yet the list has zero elements until you start adding some data to it.
You have used the ArrayList constructor that determines its initial capacity, not its initial size. The list has a capacity of 4, but nothing has been added yet, so its size is still 0.
Quoting from the linked Javadocs:
Constructs an empty list with the specified initial capacity.
Also, don't use set to add to the list. That method replaces an element that is already there. You must add to the list first (or use the other overloaded add method).

Java fixed number of elements in an array

When I create an array in Java - int array[] and array=new int[some number] -
How can I construct it if I don't know how many values it will hold so that I have enough space in it?
In that case you might wanna use ArrayList or some other dynamic collection.
You do not have to mention the size of ArrayList and you can add as many element as you want at run time. the size grows dynamically.
Declaration
List arrayList = new ArrayList();
if using JDK 1.5 or greater then you can also mention type of elements that this list will hold.
List<String> arrayList = new ArrayList<String>();
http://www.roseindia.net/java/beginners/array_list_demo.shtml
For growing arrays, use ArrayList.
If the array should contain primitive types, you can wrap them:
ArrayList<Integer> array = new ArrayList<Integer>();
array.add(new Integer(4));
array.add(new Integer(-5));
array.add(new Integer(4));
array.add(new Integer(2));
However, when the values change a lot, you keep instantiating and throwing away Integer instances, because it is immutable. It's not very high performance either.
My solution: create a wrapper yourself, with a public value field.
This is my wrapper, which is also suitable for TreeMap and the likes, which sort items by their natural order.
public class MyInteger implements Comparable<MyInteger>
{
public int value;
public MyInteger(int value)
{
this.value = value;
}
#Override
public String toString()
{
return Integer.toString(value);
}
#Override
public int compareTo(MyInteger o)
{
return value - o.value;
}
}
Now you can do stuff like:
array.get(2).value++;
ArrayList is the simplest answer, however if you want a more memory efficient approach you can use TIntArrayList (which wraps a int[])

Define a fixed-size list in Java

Is it possible to define a list with a fixed size that's 100? If not why isn't this available in Java?
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.
FixedSizeList
Yes,
The Apache Commons library provides the FixedSizeList class which does not support the add, remove and clear methods (but the set method is allowed because it does not modify the List's size). Ditto for FixedSizeList in Eclipse Collections. If you try to call one of these methods, your list remains the same size.
To create your fixed size list, just call
List<YourType> fixed = FixedSizeList.decorate(Arrays.asList(new YourType[100]));
You can use unmodifiableList if you want an unmodifiable view of the specified list, or read-only access to internal lists.
List<YourType> unmodifiable = java.util.Collections.unmodifiableList(internalList);
Yes. You can pass a java array to Arrays.asList(Object[]).
List<String> fixedSizeList = Arrays.asList(new String[100]);
You cannot insert new Strings to the fixedSizeList (it already has 100 elements). You can only set its values like this:
fixedSizeList.set(7, "new value");
That way you have a fixed size list. The thing functions like an array and I can't think of a good reason to use it. I'd love to hear why you want your fixed size collection to be a list instead of just using an array.
Typically an alternative for fixed size Lists are Java arrays. Lists by default are allowed to grow/shrink in Java. However, that does not mean you cannot have a List of a fixed size. You'll need to do some work and create a custom implementation.
You can extend an ArrayList with custom implementations of the clear, add and remove methods.
e.g.
import java.util.ArrayList;
public class FixedSizeList<T> extends ArrayList<T> {
public FixedSizeList(int capacity) {
super(capacity);
for (int i = 0; i < capacity; i++) {
super.add(null);
}
}
public FixedSizeList(T[] initialElements) {
super(initialElements.length);
for (T loopElement : initialElements) {
super.add(loopElement);
}
}
#Override
public void clear() {
throw new UnsupportedOperationException("Elements may not be cleared from a fixed size List.");
}
#Override
public boolean add(T o) {
throw new UnsupportedOperationException("Elements may not be added to a fixed size List, use set() instead.");
}
#Override
public void add(int index, T element) {
throw new UnsupportedOperationException("Elements may not be added to a fixed size List, use set() instead.");
}
#Override
public T remove(int index) {
throw new UnsupportedOperationException("Elements may not be removed from a fixed size List.");
}
#Override
public boolean remove(Object o) {
throw new UnsupportedOperationException("Elements may not be removed from a fixed size List.");
}
#Override
protected void removeRange(int fromIndex, int toIndex) {
throw new UnsupportedOperationException("Elements may not be removed from a fixed size List.");
}
}
Create an array of size 100. If you need the List interface, then call Arrays.asList on it. It'll return a fixed-size list backed by the array.
If you want some flexibility, create a class that watches the size of the list.
Here's a simple example. You would need to override all the methods that change the state of the list.
public class LimitedArrayList<T> extends ArrayList<T>{
private int limit;
public LimitedArrayList(int limit){
this.limit = limit;
}
#Override
public void add(T item){
if (this.size() > limit)
throw new ListTooLargeException();
super.add(item);
}
// ... similarly for other methods that may add new elements ...
You can define a generic function like this:
#SuppressWarnings("unchecked")
public static <T> List<T> newFixedSizeList(int size) {
return (List<T>)Arrays.asList(new Object[size]);
}
And
List<String> s = newFixedSizeList(3); // All elements are initialized to null
s.set(0, "zero");
s.add("three"); // throws java.lang.UnsupportedOperationException
This should work pretty nicely. It will never grow beyond the initial size. The toList method will give you the entries in the correct chronological order. This was done in groovy - but converting it to java proper should be pretty easy.
static class FixedSizeCircularReference<T> {
T[] entries
FixedSizeCircularReference(int size) {
this.entries = new Object[size] as T[]
this.size = size
}
int cur = 0
int size
void add(T entry) {
entries[cur++] = entry
if (cur >= size) {
cur = 0
}
}
List<T> asList() {
List<T> list = new ArrayList<>()
int oldest = (cur == size - 1) ? 0 : cur
for (int i = 0; i < this.entries.length; i++) {
def e = this.entries[oldest + i < size ? oldest + i : oldest + i - size]
if (e) list.add(e)
}
return list
}
}
FixedSizeCircularReference<String> latestEntries = new FixedSizeCircularReference(100)
latestEntries.add('message 1')
// .....
latestEntries.add('message 1000')
latestEntries.asList() //Returns list of '100' messages
If you want to use ArrayList or LinkedList, it seems that the answer is no. Although there are some classes in java that you can set them fixed size, like PriorityQueue, ArrayList and LinkedList can't, because there is no constructor for these two to specify capacity.
If you want to stick to ArrayList/LinkedList, one easy solution is to check the size manually each time.
public void fixedAdd(List<Integer> list, int val, int size) {
list.add(val);
if(list.size() > size) list.remove(0);
}
LinkedList is better than ArrayList in this situation. Suppose there are many values to be added but the list size is quite samll, there will be many remove operations. The reason is that the cost of removing from ArrayList is O(N), but only O(1) for LinkedList.
The public java.util.List subclasses of the JDK don't provide a fixed size feature that doesn't make part of the List specification.
You could find it only in Queue subclasses (for example ArrayBlockingQueue, a bounded blocking queue backed by an array for example) that handle very specific requirements.
In Java, with a List type, you could implement it according to two scenarios :
1) The fixed list size is always both the actual and the maximum size.
It sounds as an array definition. So Arrays.asList() that returns a fixed-size list backed by the specified array is what you are looking for. And as with an array you can neither increase nor decrease its size but only changing its content. So adding and removing operation are not supported.
For example :
Foo[] foosInput= ...;
List<Foo> foos = Arrays.asList(foosInput);
foos.add(new Foo()); // throws an Exception
foos.remove(new Foo()); // throws an Exception
It works also with a collection as input while first we convert it into an array :
Collection<Foo> foosInput= ...;
List<Foo> foos = Arrays.asList(foosInput.toArray(Foo[]::new)); // Java 11 way
// Or
List<Foo> foos = Arrays.asList(foosInput.stream().toArray(Foo[]::new)); // Java 8 way
2) The list content is not known as soon as its creation. So you mean by fixed size list its maximum size.
You could use inheritance (extends ArrayList) but you should favor composition over that since it allows you to not couple your class with the implementation details of this implementation and provides also flexibility about the implementation of the decorated/composed.
With Guava Forwarding classes you could do :
import com.google.common.collect.ForwardingList;
public class FixedSizeList<T> extends ForwardingList<T> {
private final List<T> delegate;
private final int maxSize;
public FixedSizeList(List<T> delegate, int maxSize) {
this.delegate = delegate;
this.maxSize = maxSize;
}
#Override protected List<T> delegate() {
return delegate;
}
#Override public boolean add(T element) {
assertMaxSizeNotReached(1);
return super.add(element);
}
#Override public void add(int index, T element) {
assertMaxSizeNotReached(1);
super.add(index, element);
}
#Override public boolean addAll(Collection<? extends T> collection) {
assertMaxSizeNotReached(collection.size());
return super.addAll(collection);
}
#Override public boolean addAll(int index, Collection<? extends T> elements) {
assertMaxSizeNotReached(elements.size());
return super.addAll(index, elements);
}
private void assertMaxSizeNotReached(int size) {
if (delegate.size() + size >= maxSize) {
throw new RuntimeException("size max reached");
}
}
}
And use it :
List<String> fixedSizeList = new FixedSizeList<>(new ArrayList<>(), 3);
fixedSizeList.addAll(Arrays.asList("1", "2", "3"));
fixedSizeList.add("4"); // throws an Exception
Note that with composition, you could use it with any List implementation :
List<String> fixedSizeList = new FixedSizeList<>(new LinkedList<>(), 3);
//...
Which is not possible with inheritance.
You need either of the following depending on the type of the container of T elements you pass to the builder (Collection<T> or T[]):
In case of an existing Collection<T> YOUR_COLLECTION:
Collections.unmodifiableList(new ArrayList<>(YOUR_COLLECTION));
In case of an existing T[] YOUR_ARRAY:
Arrays.asList(YOUR_ARRAY);
Simple as that
To get a fixed-size list, you can simply use the Stream API. This will result in a fixed-size list :
List<Integer> list = Arrays.stream(new int[100])
.boxed()
.collect(Collectors.toList());
Or the old-fashioned way, This will result in a fixed-size list that is backed by the specified array:
List<Integer> list = Arrays.asList(new Integer[100]);
Yes is posible:
List<Integer> myArrayList = new ArrayList<>(100);
now, the initial capacity of myArrayList will be 100

How to get a sublist without using the sublist method in java

This is what I have right now:
public ArrayList subList(int fromIndex, int toIndex){
ArrayList a = new ArrayList();
for (int i=fromIndex;i<toIndex;i++) {
a.add(stuff[i]); //stuff is a array of strings
}
return list;
}
But is it possible to return the sublist without creating a new array? I am restrict from using any methods from the Array/ArrayList class.
If you want have the same behaviour as the Java subList method you need to retain a pointer to the original list and use an offset and length to index into the original list.
Heres a start showing the implementation of the get method.
public class SubList extends AbstractList {
private final List original;
private final int from;
private final int to;
public SubList(List original, int from, int to) {
this.original = original;
this.from = from;
this.to = to;
}
public Object get(int i) {
if (i < 0 || i > to - from) {
throw new IllegalArguementException();
}
return original.get(from + i);
}
}
public static List subList(List original, int from, int to) {
return new SubList(original, from, to);
}
To avoid creating a new list for storage, you would have to pass in a reference to the original list, keep the sublist, and then delete the remaining items from from the list, but this would leave the list missing those other items.
If that isn't your goal you will have to create a new list at some point to hold the sublist.
I assume you have to return the standard ArrayList, and not your own version of ArrayList, and I assume that 'stuff' is an array, not a list.
First off, get bonus points for making the ArrayList have the initial size of the array (toIndex - fromIndex). For more bonus points, make sure that the to and from indecies actually exist in 'stuff' otherwise you get a nice crash.
ArrayList uses an internal array for its storage and you can't change that so you have no choice but to create a copy.
EDIT
You could make things interested and much more complex but it'll impress someone... Do it by creating your own ArrayList class implementing List. Get it to use that original array. Pretty unstable since if that array is modified somewhere else externally, you're in trouble, but it could be fun.
There's three sensible things you could return. An array, a List, or an Iterator. If my assumption that you're supposed to re-implement subList was correct, then there's no way around creating the new ArrayList.
A sublist is "a new list", so you'll have to create something to represent the sublist of the array. This can either be a new array or a list. You chose an ArrayList which looks good to me. You're not creating a new array (directly), so I don't actually get that point of your question. (If you want to avoid creating a new array indirectly through ArrayList, choose another List implementation, LinkedListfor example)
If you're looking for slight improvements:
Consider passing the source array as a method parameter. Now stuff[] is a static field.
Consider initializing the new ArrayList with the size of the sublist (toList-fromList+1)
Consider using generics (only if you already now this concept). So the return type would be ArrayList<String>

Categories