Regarding creation of dynamic array in java - java

Could you please advise how to create a dynamic array..!! A primitive array can be declared as
int[] myIntArray = new int[3];
But this time I know know the size of array is of 3 elements but what if I want to create a dynamic array how I will create that, Please advise.

An array has always to be initialised with a given size. Use a List if you wish to have a 'dynamic' collection and then convert to an array if needed. The array cannot be resized after instantiation whereas a List can (ignoring non modifiable lists).

You can instantiate an array using a variable, but once instantiated, the array will be stuck at that size.
int[] myArrayInt = new int[arraySizeVariable];
If you want something that is truly dynamic then I would suggest using an ArrayList instead.
List<Integer> myArrayList = new ArrayList<Integer>();

ArrayLists can grow and shrink dynamically:
ArrayList<Integer> list = new ArrayList<Integer>();
//...
list.add(5);
list.add(1);
//...
int index = list.indexOf(5);
list.remove(index);

use java.lang.reflect.Array
public static Object newInstance(Class<?> componentType, int length) {}

In Java you can have all sorts of dynamic groups of elements. The basic array [] is still going to be as static as it will in any other similar language, so you are going to want to use some implementation of the Collection.java interface.
The most basic one is a Vector which simply contains some objects, not necessarily of the same class, and will grow dynamically as you add or remove items from it. If you want them to be ordered then you can use an implementations of List.java. If you want the collection to be unique then you can use instances of Set.java.

public int[] createArray(int size){return new int[size];}
Well it's a dumb code. Creates array of size you want. It's not expandable once created. For that you need to expand manually by copying to a larger array when your old array is full. Or better, get it done by a collection called ArrayList, which doubles capacity when reaches to some threshold.
If you implement your own expandable array, it will be same as using ArrayList: see
Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

Related

Java - Difference between fixed-sized list and list with initial capacity specified

I am having an issue in understanding this.
while we do
List<Integer> list = Arrays.asList(array);
we can not use methods like add, remove on that list. I know that Arrays.asList() returns a fixed-sized list.
What I don't understand is if we create a list with initial capacity specified like
List<Integer> list2 = new ArrayList<Integer>(10);
we can perform all the operations on that list. What is the difference between fixed-sized list and list with initial capacity specified?
I have read many answers on this but having such a hard time understanding this. Can anyone explain?
Thanks.
Arrays.asList(array) returns an object of type java.util.Arrays.ArrayList, which does not support add and remove operations.
While the code below will return an object of type java.util.ArrayList, which supports add and remove operations.
List<Integer> list2 = new ArrayList<Integer>(10);`
Very simply, Arrays.asList is so you can use List methods with an array. ArrayList(int) is for when you need to create a really large ArrayList and want to help speed things up a bit.
In more detail: the List returned by asList is intended as a wrapper to an array. Since you cannot resize an array, the methods that change the size of a List are unimplemented. Most of the time I just use asList to add a fixed number of elements to a collection simply. eg.
new ArrayList<String>(Arrays.asList("hello", "world"));
Confusingly, the implementation of ArrayList is very similar -- it's a List backed by an array. However, ArrayList allows you to change it's size. To do this it keeps a separate fields about the how many objects are in the list and the length of the backing array. Add an element and the ArrayList just sets array[size] to the element and then increments the size field. But what if array[size] is out of bounds? At this point the ArrayList creates a new, larger array and copies over the elements from the previous backing array. However, if you are creating a large List then this constant creation of new backing arrays can start to take up a lot of time. As such, if you know the approximate number of elements that will be in the List you can use this to inform the ArrayList about the size of the initial backing array it should create. This is what the ArrayList(int) constructor is for. Only in exceptional circumstances will you need to worry about giving the ArrayList a length hint.

If I have fixed size data, should I go for array and arraylist?

Suppose I have 10 integers. Now, as I know the size of data which one should i use array or ArrayList and why?
ArrayList<?> list = new ArrayList<>();
For a fixed size data, the most simple data structure is an array. ArrayList wouldn't take much more memory, though, as it is backed by an array (and the default initial capacity of an ArrayList is 10, so in your case the sizes of the arrays being used in both cases would be the same).
An advantage to using arrays is that they can hold primitives, while ArrayList can only hold reference types.
An int[] is more efficient than ArrayList<Integer>.
ArrayList fits your need. It is fast.
List<Integer> list = new ArrayList();
list.add(1);
list.add(2);
Arrays are much faster because array[10] is faster to access than array.get(10), as the latter internally does the same call, but adds the overhead for the function call plus additional checks.
So for a known limited size you will always opt for Arrays over ArrayList
Array always take lesser memory than Arraylist.
If you are only going to store integers, Array list is the best option.

Java array declaration without hard coding the size

How can I initialize an array of objects of a class in another class without hardcoding its size?
Use a List. The size does not need to be declared on creation of the List. The toArray() method will return an array representation of the list. There are multiple implementations you can use but the most popular tends to be ArrayList (though it is best to map the implementation to your particular situation).
Arrays have a fixed size after creation. The size doesn't need to be known at compile-time, but it does need to be known at creation time. For example:
public String[] createArray(int size) {
// Not hard-coded, but array is not expandable
return new String[size];
}
If you want a collection which can grow an shrink over time, look at the various List<E> implementations, such as ArrayList<E>.
Arrays are fixed in length. I would recommend using a Collection.
Here is an article on collections:
http://en.wikipedia.org/wiki/Java_collections_framework
With these, you can add elements by using an Add() command or something similar.
As mentioned in the previous answers, an ArrayList or List are collections.
Object[] will always be fixed size. If you need a variable length collection, try ArrayList, LinkedList, or one of the many others.
Pick the collection carefully, since they all have different performance aspects.
For mutable arrays other container objects are used.
When using a set of objects, an ArrayList or Vector object is used.
You can also store objects with an object key e.g. "Name" = "Ben" instead of [0] = "Ben".
Vector v = new Vector();
for(int i = 0; i < 100; i++){
Object o = new Object();
// init object
v.addElement(o);
}
for(int i = 0; i < 100; i++){
Object o = v.elementAt(i);
// manipulate object
}
Now you have an arbritairy list of object of undefined length.
Size found by using vector.size() method.
java.util package is required and part of J2SE 1.3 and higher.
As noted elsewhere, an array object has a fixed size. If there's some reason you must use an array, you can use one or both of these techniques:
Make it the larger than you need, leaving the unused
entries null. You may want to keep a "slotsUsed" variable.
When the array gets too small, make a bigger one and copy the
contents into it.
These are both used inside ArrayList.
You can create a new array and initialize it like this.
String[] strArray = {"Initialize","Array","Like","This"};
If you want an array with a dynamic size I would recommend using an ArrayList.
If you want an array of primitive instead of objects, you can use Trove4j. Otherwise use an ArrayList, or CopyOnWriteArrayList to wrap an array. There are other List implementations but these do not act like arrays for access time.
Sometimes it is useful, in case you know an upper bound of the objects your application needs,
to declare the size of an array as
static final int ARRAY_SIZE = 1000;
This goes near the beginning of the class so it can be easily changed.
In the main code instantiate the array with
Object[] objects = new Object[ARRAY_SIZE];
Also in case the array you want to use has the same size as another array consider using
Object[] objects = new Object[other_objects.length];

java.lang.IndexOutOfBoundsException: Source does not fit in dest

On the following code:
static void findSubsets (ArrayList<Integer> numbers, int amount, int index)
{
ArrayList <Integer> numbersCopy = new ArrayList<Integer>(numbers.size());
Collections.copy(numbersCopy, numbers);
}
I'm getting the error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Source does not fit in dest
at java.util.Collections.copy(Collections.java:548)
at backtracking2.Main.findSubsets(Main.java:61)
Why?
Capacity does not equal size. The size parameter that you are passing in simply allocates enough memory for the size. It does not actually define elements. It's actually kind of a silly requirement of Collections.copy, but it is one nonetheless.
The key part from the Collections.copy JavaDocs:
The destination list must be at least as long as the source list. If it is longer, the remaining elements in the destination list are unaffected.
You should just pass the List to the ArrayList's constructor to copy all of the List to avoid the issue altogether.
That's a very good question and it almost certainly has to do with the fact that setting a collections capacity does not necessarily allocate the underlying objects, but why are you doing it that way when you can just:
ArrayList <Integer> numbersCopy = new ArrayList<Integer>(numbers);
The constructor ArrayList(Collection<? extends E> c) will copy every elements from c into the newly created instance, thus copying numbers into numbersCopy. It is the same as numbersCopy.addAll(numbers) also, which is really what you need.
It does make sense that Collection.copy requires the dest array to be large enough to hold all elements from the source array. A similar analogy is the C function memcpy and the like.
While creating an ArrayList to copy another ArrayList using Collections.copy() method, we need to make sure that the destination List contains same number of values (not just same size) as source List. For example, if source ArrayList has values [Red,Blue,Green], then the destination ArrayList should also contain same number of elements like [Orange,Yellow,Blue].If we create an ArrayList with same size that of source ArrayList, it will give OutOfBounds exception.
You can also use, Collections.addAll
like Assume we need to copy List1 to List2, then
List2.addAll(List1);
Here the files will be added, if you want it more efficient then make sure you clear the list2 before adding the items of list1, like this,
list2.clear();
In java 8 +
List<Integer> numbersCopy = numbers.stream().collect(Collectors.toList());
It easier in java 10+
List<Integer> numbersCopy = List.copyOf(numbers);
List.copyOf() returns an unmodifiable List containing the elements of the given Collection.

Variable length (Dynamic) Arrays in Java

I was wondering how to initialise an integer array such that it's size and values change through out the execution of my program, any suggestions?
Yes: use ArrayList.
In Java, "normal" arrays are fixed-size. You have to give them a size and can't expand them or contract them. To change the size, you have to make a new array and copy the data you want - which is inefficient and a pain for you.
Fortunately, there are all kinds of built-in classes that implement common data structures, and other useful tools too. You'll want to check the Java 6 API for a full list of them.
One caveat: ArrayList can only hold objects (e.g. Integers), not primitives (e.g. ints). In MOST cases, autoboxing/autounboxing will take care of this for you silently, but you could get some weird behavior depending on what you're doing.
Arrays in Java are of fixed size. What you'd need is an ArrayList, one of a number of extremely valuable Collections available in Java.
Instead of
Integer[] ints = new Integer[x]
you use
List<Integer> ints = new ArrayList<Integer>();
Then to change the list you use ints.add(y) and ints.remove(z) amongst many other handy methods you can find in the appropriate Javadocs.
I strongly recommend studying the Collections classes available in Java as they are very powerful and give you a lot of builtin functionality that Java-newbies tend to try to rewrite themselves unnecessarily.
Arrays are fixed size once instantiated. You can use a List instead.
Autoboxing make a List usable similar to an array, you can put simply int-values into it:
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
I disagree with the previous answers suggesting ArrayList, because ArrayList is not a Dynamic Array but a List backed by an array. The difference is that you cannot do the following:
ArrayList list = new ArrayList(4);
list.put(3,"Test");
It will give you an IndexOutOfBoundsException because there is no element at this position yet even though the backing array would permit such an addition. So you need to use a custom extendable Array implementation like suggested by #randy-lance
It is recommend to use List to deal with small scale size.
If you have a huge number of numbers, NEVER use List and autoboxing,
List< Integer> list
For every single int, a new Integer is auto created. You will find it getting slow when the size of the list increase. These Integers are unnecessary objects.
In this case, to use a estimated size would be better,
int[] array = new int[ESTIMATED_SIZE];
How about using a List instead? For example, ArrayList<integer>
You can't change the size of an array. You can, however, create a new array with the right size and copy the data from the old array to the new.
But your best option is to use IntList from jacarta commons. (here)
It works just like a List but takes less space and is more efficient than that, because it stores int's instead of storing wrapper objects over int's (that's what the Integer class is).

Categories