Adding element to next free space in array - java

I have an array
String[] path={abc,bcd};
I pass this array in a method:
addElement(path);
In method
void addElement(String[] path)
{
// here i got value suppose "qsd" and i want to add it after "bcd" ie 2 index of array
path[path.lenght]="qsd";
}
But this is giving me an error.
I dont want to use an ArrayList.

The biggest problem is that arrays in Java are not trivially resizable. What you wind up doing instead is actually creating a new array, and adding each of the elements to that. This will be slower than the ArrayList code, and uglier as well.
This also means that any code which points to the old array will no longer work. If you only have one instance, you could have addElement return the new array like so
String[] addElement(String old[]){
String arr[] = new String[old.length+1];
//copy all the elements in old...
arr[old.length] = "whatever";
return arr;
}
Then use
path = addElement(path);

You should use ArrayList
Otherwise you have to resize the array by allocating new memory of the size of the original array +1, copy the elements from the old one to the new one, and add in the new element.

You can't change the size of emulated array in GWT (even if javascript arrays support this stuff). You'll have always to create a new instance of array. Most common way to solve this problem is to use one of the collection classes (like java.util.ArrayList) . Example:
ArrayList<String> path = new ArrayList<String>(Arrays.asList("abc","bbc"));
path.add("qsd");

Related

ArrayList<String> vs String[], How and when to use?

I am learning about making a ListView on Android app, and I want to know about these two, some examples use String[], and some use ArrayList....but I dont see how people adding more item in String[].
String[] is a primitive data type, a plain simple array with a fixed size which has to be known at COMPILE TIME and can't be changed at RUNTIME.
Consider:
String[] foo = new String[2];
Here you declare a simple string array which can hold 2 strings.
Let's add stuff to it:
foo[0] = "String One";
foo[1] = "String Two";
You can also forward declare it like that:
String[] foo = {"String One", "String Two"};
You can change the contents of foo but you can't add another string nor remove it since it has a fixed size.
At the other hand, ArrayList is a dynamic list where you can add or remove items of type T at any time in your program.
The size does not need to be defined at COMPILE TIME and the contents of a Arraylist can be added or removed at RUNTIME . It is the most flexible data structure of the two.
Consider:
ArrayList<String> foo = new ArrayList<>();
That declares the dynamic array. It has a variable size and there is no need to define the number of elements upon initalisation. You can add or remove elements to/from it as you like, any time at RUNTIME.
Note that:
foo.add("String One");
foo.add("String Two);
can be added at any time in your program. Same goes for removing elements. Since ArrayList is a (generic) class, it has also a bunch of helpfull methods that a plain array does not have !
Please also read about Java generics to get the full picture.
So it depends what you want to do with the ListView. If you just want to have a fixed set of strings displayed then go for String[], or you need to change the content of the view dynamically by adding or removing data, then an ArrayList might be the right one for the job.
First of all, The String[] is belong to the conventional array which means that this data size that the array is contained is fixed and cannot be changed. Otherwise, the ArrayList is not. It can grow the size as the number elements grows. Moreover, ArrayList has a set of methods to access elements and modify them. But, the ArrayList just can store Object and the storing speed is more slower.
For the answer why in a ListView or RecyclerView, most of cases, we use the ArrayList instead of Array because of the ability of extension in ArrayList. For example, in the NoteApp, if you use the Array, you must set the fixed allocate numbers for the notes, but if you adding the new note, you must change it programmatically. It cannot adapt the size to contain the new note. So that, the ArrayList is suitable for this case.

Is there a way of setting the size of an arraylist after declaring it?

For example, in a traditional array, i would declare an array like this:
int array[];
then, i would later initialize it like this
array = new int[1000];
in an arraylist i am trying to do the same but I have only been able to initialize it while declaring it like below.
ArrayList<String> array = new ArrayList<>(1000);
it's almost the same as
int[] array = new int[10000];
So I would like to know if there's a way to initialize an arraylist to for example 1000 after it's been declared in a separate statement.
You can use ensureCapacity(int)
ArrayList<Integer> al = new ArrayList<>();
al.ensureCapacity(1000);
It is important to note that array lists WILL dynamically resize themselves though.
So I would like to know if there's a way to initialize an arraylist to for example 1000 after it's been declared in a separate statement.
You could always do this, too:
ArrayList<Integer> al;
al = new ArrayList<Integer>(1000);
This is more akin to the regular array initialisation.
it is not same as declaring size for array, it is initial size you are passing in
you can still go beyond 1000 runtime in case of List and not in array
ArrayList dynamically will grow the size as required, 1000 here is initial size of array wrapped under ArrayList
There's no reason to do this besides performance reasons, but you can use the ensureCapacity method.
ArrayList<String> array = new ArrayList<String>(100);
//code, code, code, ask user size of ArrayList
array.ensureCapacity(someUserInputSize);
I would like to know if there's a way to initialize an arraylist to for example 1000 after it's been declared in a separate statement.
You can declare it first, then initialize it later, just like with the array:
ArrayList<String> array;
...
array = new ArrayList<>(1000);
But just so you know, the argument of this ArrayList(int) constructor is the initial capacity of the backing array, rather than the size - it's merely an optimization one can do if the expected size of the ArrayList is known. An ArrayList instantiated this way will still be empty until elements are added.

continuously changing array size [duplicate]

This question already has an answer here:
How to manage Continuous Changing values in an array of strings [closed]
(1 answer)
Closed 9 years ago.
I have an array of strings but the values in array is changing continuously.
Is there any other way of managing the array except removing items and changing index locations?
public String[] deviceId=null;
deviceId=new String[deviceCount];
in my case deviceCount is changes as new device comes.
so i continuously need to change array size and add or remove items
Use ArrayList in place of String[] ..
And you can also easily cast ArrayList to String[] for your final output as
ArrayList<String> mStringList= new ArrayList<String>();
mStringList.add("ann");
mStringList.add("john");
String[] mStringArray = new String[mStringList.size()];
mStringArray = mStringList.toArray(mStringArray);
You could use a List. It changes size depending on how many objects you put in it.
List<String> list = new ArrayList<String>;
public static void main(String[] args) {
list.add("string 1"); //Add strings to the list
list.add("string 2");
System.out.println(list.get(0)); //Get the values from the list
System.out.println(list.get(1));
}
Instead of using Arrays, you could use ArrayLists. You can add as much as you want to them without having to re-size the array and once you no longer need an item it can be removed. Here is a link to an overview of ArrayLists and some examples using them: http://www.tutorialspoint.com/java/java_arraylist_class.htm
Hope this helps.
If you know the max count of devices. Then you can define an array with max size.
String[] deviceId = new String[MAX_DEVICE_COUNT];
Or else simply go with a List.
List<String> deviceId=new ArrayList<String>();
Don't worry about performance, so much with a array.
- In Java arrays are initialized at the time of its creation whether its declared at class level or at local level.
- Once the size is defined of an array in Java it can't be changed.
- Its better to use Collection like List.
- It has the flexibility to add and delete the items in it, and one can also at items at desired location in the List.
- List is an Interface in Java, you can use its concrete sub classes like ArrayList, LinkedList..etc.
Not sure whether i got the question correctly but you can use ArrayList or LinkedList if the size is going to change dynamically.

Expanding an Array? [duplicate]

This question already has answers here:
Java dynamic array sizes?
(19 answers)
Closed 9 years ago.
I know you can't dynamically expand a normal array but is this a valid way of doing it?
public int size = 0;
public String[] OrigArray = new String[size+1];
public void expand(){
String[] tempArray = new String[size+1];
tempArray = (String[])OrigArray.clone();
OrigArray = new String[size+1];
OrigArray = (String[])tempArray.clone();
size++;
}
I'm aware of much better methods than trying to use a normal array but I'd like to figure this for just using a normal array first.
My desire is that it starts off with OrigArray being 0+1 (so 1) and when expand() is called the new tempArray is made that is the same size as the OrigArray and this then holds OrigArray while OrigArray is declared again with size+1 then the tempArray is copied back to the newly sized OrigArray. This makes sense to me, but I keep getting out of bound exception?
The method does not change the value of OrigArray; all it does is store a clone of a clone in it, so in effect the value isn't changed.
I think what you want is this:
public void expand() {
String[] newArray = new String[OrigArray.length + 1];
System.arraycopy(OrigArray, 0, newArray, 0, OrigArray.length);
//an alternative to using System.arraycopy would be a for-loop:
// for(int i = 0; i < OrigArray.length; i++)
// newArray[i] = OrigArray[i];
OrigArray = newArray;
}
This creates an array that has a size 1 greater than OrigArray, copies the content of OrigArray into it and assigns that array to OrigArray. Unless you want to remember how many times expand() has been called, there shouldn't be a reason to have the variable size.
EDIT: If what you really want is to know a way to sensibly implement the functionality you asked for, you can go with what #Óscar López said and use ArrayList.
What you're trying to accomplish by hand, it's pretty much what ArrayList does for you - use that class, instead.
Under the hood, ArrayList uses an Object[] for storing items, under a certain capacity constraint. When the array is filled (as new items are added), a new array with doubled size is created and all the items in the original array are copied in it. All this happens automatically, and it's transparent for the programmer.
Given that in the sample code you're storing an array of objects (Strings), there'll be little difference in performance if you use an ArrayList for storing them, so there's no real reason to reinvent the wheel!
No, that is not a valid way to do it. What you are doing is actually
First create a new larger array
Throw away the newly created array and copy the original array
Create year another new array with larger size
Throw away the newly created array and clone the already cloned array again
For non primitive types I think you want to use the ArrayList
However, if you want to build this for primitive types, this is how you would do it
public int size = 0;
public int[] origArray = new int[size+1];
public void expand(){
int[] tempArray = new int[size+1];
System.arrayCopy(origArray, 0, tempArray, 0, size);
origArray = tempArray;
size++;
}
You probably want to hide the data behind accessors (get...() methods) and you do not want to just expand the array by one element at a time, creating and copying arrays is costly.
This:
OrigArray = new String[size+1];
OrigArray = (String[])tempArray.clone();
is essentially equivalent to just this:
OrigArray = (String[])tempArray.clone();
in that the second assignment completely supersedes the first. OrigArray will end up having the same size as tempArray, and therefore the same size that it originally had.
If you want to copy elements into an existing array, you have to either write a loop, or else use java.lang.System.arrayCopy(...) which handles the loop for you; but calling clone() on an array will always create a new array, so will not help.
Your method won't work because clone() will just reassign the array to the original size. I would recommend using
System.arraycopy(OrigArray, 0, tempArray, 0, OrigArray.length);
instead.
Also, the most efficient way of doing this would be to use an ArrayList, since they implement practically the same thing, but clean up your code a lot.
The only problem is when you need to get a regular array of the value's type, then you would have to do this:
String[] asArr = new String[OrigArray.length];
for(int i = 0; i < OrigArray.length; i++)
asArr[i] = OrigArray.get(i);
Here is the Javadoc for ArrayList:
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/ArrayList.html
Take a look at System.arraycopy -- it copies one array to the other (you can also do this yourself in a loop, though arraycopy is a bit faster). So the general pattern is to create a new array that's bigger than the first, then copy the first's elements into the bigger one, and then update your field/variable to point to this new, bigger array.
Constantly constructing and destructing objects in memory is costly and slow. I would write a class that stores a little extra space (maybe 3-5 extra items), similarly to how List works, and when querying the size only output the used spaces and only expand when exceeding this buffer space. This can greatly improve performance.

Dynamic array declaration in java

can anyone tell me the error in this java declaration String[][] t=new String[15][15]; this works fine and if i use String[][] t=new String[][]; because i need to declare the variable t as dynamic as i am not sure how much values i am going to store in t.
Use ArrayList (or other array object who can handle any number of objects). A java array always has a fixed length since some memory will be reserved for the array.
ArrayList creates such array as well to store the objects. Of you add more abjects as the current reserved size of the array than ArrayList will create a new bigger array (+50% if i'm correct). There are some other implementations that act a bit different (for example they create a new array 100% of the original one when the array is full. If performance is really important for you than you can look into this.
ArrayList<ArrayList<String> t = new ArrayList<ArrayList<String>();
void fill() {
ArrayList<String> t2 = new ArrayList<String>();
t2.add("somestring");
String s = "someotherstring";
t2.add(s);
t.add(t2);
}
If you don't know how big it needs to be just declare it as
String[][] t;
and once you know how big it needs to be you can do (before trying to use the array)
t = new String[15][15];
If you're never sure how big the array need to be, you'll need to use something like a List of Lists.
List<List<String>> t = new ArrayList<List<String>>;
public void add(String str, int row, int col) {
while (row >= t.size())
t.add(new ArrayList<String>());
List<String> row_list = t.get(row);
while (col >= row_list.size())
row_list.add("");
row_list.set(col, str);
}
In Java array objects are always of fixed length. Once you have allocated them you cannot change their size. An array variable can be made to point to different array objects of different size. So you can allocate:
String[][] t;
which doesn't point to an object and allocate an object later once you know the size:
int n1,n2;
// calculate n1,n2
t = new String[n1][n2];
If you need a structure where the size can change you are much better off using ArrayList, which can be dynamically resized.
Declare it as String [][]t = null;
And Reinitialize it with actual length once you get it.
t=new String[x][y];
As bemace said, just because you are declaring the variable doesn't mean you have to initialize it immediately.
As Mark said, arrays have a fixed size. Once an array is initialized(not declared, initialized) it has a fixed size.
So, there are two possibilities:
Either you will know how big the array needs to be before you need to start using it, in which case you can simply delay your initialization as suggested by bemace.
Or you won't know how big it needs to be before you start using it, in which case you need to use a dynamically sized data structure(s). Check out the Java Collections API:
tutorial
api reference
There are several good answers already, but it has now been revealed in a comment to Mark Baijens' answer that the purpose of this question is that raju need a key to multi-value mapping.
Mark followed up that comment by suggesting raju use a HashMap<String, String> hashMap = new HashMap<String, String>(); — however that only works for a single key-value pair.
What raju needs is a
Map<String, Collection<String>> t
= new HashMap<String, List<String>>();
Adding the first value for a key requires initialization of a List for that bucket, while adding additional values requires fetching the existing list and adding the new value.
Note I used Collection<String> in the declaration, so it could be a List if the order of values is important, or it could be a Set to prevent duplicate values under the same key.
This would probably be best implemented as a Class itself, perhaps
public class MultiValueMap<K, V> extends Map<K, V>
{
...
}
so the initialization of the List on the first put(key, value) and the subsequent .add(value) to the list could be hidden in the implementation.

Categories

Resources