Adding values to already initialized object array in Java? - java

I'm developing for the Android platform and, to simplify the question, I'm using pseudo-names for the entities.
I have an object array stuff[] of the class StuffClass[].
StuffClass stuff[]={
new StuffClass(Argument, argument, argument),
new StuffClass(argument, argument, argument)
};
I have an activity returning a result of three arguments that I want to then use to add a new object to stuff[]. I've done so as follows:
stuff[stuff.length]=new StuffClass(argument, argument, argument);
and I get ArrayOutOfBounds (Figured that would happen).
So how might I go about creating a new object in the stuff[] array?

Arrays are static you can't change size without creating a new one before. Instead of that you can use a dynamic data structure such as an ArrayList
Example:
List<MyType> objects = new ArrayList<>();
objects.add(new MyType());
Here you forget about array size.

Array in Java is little bit special, it's length is fixed when it's initialized, you can not extend it later on.
What you can do is to create a new array, and use System.arraycopy to generate a new array, here's the sample code:
String[] arr1 = new String[]{"a", "b"};
String[] arr2 = new String[3];
System.arraycopy(arr1, 0, arr2, 0, 2);
arr2[2] = "c";

You cannot increase the size of an existing array. Once it's created, the size of the array is fixed.
You will need to create another bigger array and copy the items from the old array to the new array.
A better alternative is to use an ArrayList. When you add items to an ArrayList, the capacity will grow behind the scenes if needed; you don't have to worry about increasing the size.

you can use the ArrayList to do this
arraylist.add(object);

in java arrays are fixed length. you need to initialise them with the desired length.
Consider using a Collection such as ArrayList which will handle everything for you.
List<StuffClass> myList = new ArrayList<>();
myList.add(...);
Lists support similar behaviour to arrays ie:
myList.set(i, elem);
myArray[i] = elem;
elem = myList.get(i);
elem = myArray[i];
len = myList.size();
len = myArray.length;
You can then convert the list to an array.
StuffClass[] myArray = myList.toArray(new StuffClass[myList.size()]);
If you don't want to use lists consider using System.arrayCopy to create a new array with more elements.
read here for a good description.

Related

Change size of an array by an arraylist

One of the main Charucteristic of the Array is immutability(Size of the array cant be changed) but while i was practicing i found myself in this case :
We have an Array with specific size
String[] strArr = new String[1];
And ArrayList with Objects
ArrayList<String> list = new ArrayList<>();
list.add("Alex");
list.add("Ali");
list.add("Alll");
So when we try to convert the list to an array and assign it to strArr , like this
strArr = list.toArray(strArr);
for(String str : strArr ) {
System.out.println(str);
}
It works without a problem even if the size of the array doesnt equal the size of the list
So I JUST WANT TO KNOW HOW THIS IS POSSIBLE , WHEN THE SIZE OF THE ARRAY CANT BE CHANGED ?
New array allocated
strArray first references to a String array of size 1, when you do strArr = list.toArray(strArr);, you change the reference of strArray to a different array. So you are not changing the array size, you are only changing to which array now strArrays refers to.
Possibly you assume that list.toArral(strArr) modifies strArr but that's not the case, as you can read at the java documentation. It reads:
"If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list"
The important section for your case, is where the documentation says: "Otherwise, a new array is allocated", so, no array resize is done.
You can use
strArr = list.subList(0, strArr.length).toArray(strArr);
Basicaly, the List#subList(fromIndex, toIndex) creates a new List with the elements starting in the fromIndex up to toIndex (self-explaintory)
You can read more about in https://docs.oracle.com/javase/8/docs/api/java/util/List.html#subList-int-int-
It changes the reference to a new object. You can check this by calling: System.out.println(strAttr) immediately after you first assign the variable and then again after you call strArr = list.toArray(strArr);

How to append data into a String list in Java

I am new to Java and Here is my code.
String[][] datas={{"a","b","c"},{"d","e","f"},{"g","h","i"}};
String[] onedata={"j","k","l"};
the thing I want to do here is that, I want to append the onedata into datas at last index value.
Please help let me know that how can I do this.
You can use an ArrayList because their sizes are mutable. For example:
String[][] datas={{"a","b","c"},{"d","e","f"},{"g","h","i"}};
List<String[]> datasList = new ArrayList<>(Arrays.asList(datas));
String[] onedata = {"j","k","l"};
datasList.add(onedata);
datas = datasList.toArray(new String[datasList.size()][]);
The things you are dealing with are arrays (String[]) and multidimensional arrays (String[][]) in Java, not lists. Their length is fixed. Therefore to append a new item to an array in such way that the length increases (so not by replacing the last item in the current array) you would need to create a new array with length n+1, assign the old values to the first n indices and then the new value to the index n+1.

How to add values to Double[] arraylist [duplicate]

This question already has answers here:
I'm getting an error in my Java code but I can't see whats wrong with it. Help?
(5 answers)
Closed 5 years ago.
I created this arrayList:
Double[] arrayOfNumbers = new Double[List.size()];
And I try to add it numbers with this:
arrayOfNumbers.add(0.9);
This gives me an error message that says:
Cannot invoke add(double) on the array type Double[]
So, how can I add that value in this Double[] arraylist?
That is not an ArrayList. That is an array.
You can declare an arraylist of doubles as :
int initialCapacity = 20;
List<Double> doubles = new ArrayList<Double>(initialCapacity);
doubles.add(0.9);
You can add more than 20 values in an ArrayList even though the initial capacity is specified as 20.
But to declare an array and populate it:
double[] doublesArray = new doubles[20];
doubles[0] = 0.9;
doubles[1] = 0.5;
.....
doubles[19] = 0.7; // 19 is the last index for an array of size 20.
If you add more than 20 here, you will get ArrayIndexOutOfBoundsException
Double[] is not ArrayList to add to an array you can use :
Double[] arrayOfNumbers = new Double[List.size()];
arrayOfNumbers[0] = 0.9;
Instead to add to an ArrayList you can use :
List<Double> arrayOfNumbers = new ArrayList<>();
arrayOfNumbers.add(0.9);
Arrays and lists are different things. Arrays don't have an add method, but are assignable by the subscript ([]) operator:
arrayOfNumbers[0] = 0.9;
Double[] arrayOfNumbers = new Double[List.size()] is not a List
it is an array.
We declare arrays with [] and lists with <> and generics.
For example `
int[]arr=new int[3] is an array of 3 ints, but List<Integer>list=new ArrayList<>() is a list of integers(not primitive ints you CANNOTwrite code like this List<int>=new ArrayList<>()
Hope that helps!
java.util.List is a different that an array(which has limited predefined size).
you can't declare/perform as above you did in question, java compiler will complain if you do so.
you are phasing a error like,
Cannot invoke add(double) on the array type Double[]
because an array(arrayOfNumbers) do not having a such method(add) which you can execute on arrayOfNumbers.
However,
general syntax to initialize of an array of any type(here in example, Integer taken FYI) is likewise,
int intArray[] = {1,2,3}; // initialize at the time of creation
or
int arrayOfNumbers [] = new int[] {1, 2, 3};
or
intArray[index] = 1;
Moreover, you can switch from array to List & vice-versa as likewise,
List<Integer> list = java.util.Arrays.asList(arrayOfNumbers);
or
Integer [] intArray = list.toArray(new Integer[list.size()]);
A List is an Interface that extends another interface called Collection, so a List is-a Collection. An Interface defines and describes behavior, it defines a contract that another class must conform to, and one of the classes that does so is called java.util.ArrayList, and add() is one behaviour defined in the List contract, because a List must have the ability for things to be added to it. An ArrayList is one type of a List. What you have created is NOT an ArrayList, it is an Array.
An array is a primitive data structure, once created, it's size cannot be changed, If you wish to add a new element to an array you have to create a new array that is bigger, then transfer all elements from the old array to the new one. Under the covers an ArrayList does exactly that. THIS IS HOW YOU CREATE an ArrayList :
//a list of Objects of type `Double`
List<Double> listOfNumbers = new ArrayList<>();
if you wish to add an element to this list, you would do this :
listOfNumbers.add(5.2);
You do seem like you still need to read a beginners book and practice basic Java programming. I would like to suggest this playlist
This will really be helpful to you, and remember you can only learn something by doing it hands-on, NOT by just watching somebody else doing it.

How can add an element to an array?

I wrote this code with a String array:
public static String[] prgmNameList = {"bbbbb", "aaaaa"};
My question is now, how can I add a new item to that array like this:
prgmNameList.add("cccc");
prgmNameList is an array. The size of an array object cannot be changed once it has been created. If you want a variable size container, use collections. For example, use an ArrayList :
List<String> prgmNameList = new ArrayList<String>(3);
prgmNameList.add("bbbb");
That said, if you insist on using an array, you will need to copy your initial array into a new array for each new element that you want to add to the array which can be expensive. See System#arrayCopy for more details. In fact, the ArrayList class internally uses an array that is expanded once it is full using System.arrayCopy so why reinvent the wheel? Just use an ArrayList
On simpler terms, note these following points:
Array size is always fixed.(In your example you fixed the array size to 2 by adding 2 elements)
Arrays operate based on index starting from '0' zero, like - prgmNameList[0] will return 1st element added in the array
Array size cannot be changed at any point of time. If you need size to be variable, choose one of List implementations
ArrayList is the best option for your need that can define itself as an 'Array that can shrink or grow'
Sample code:
public static List<String> prgmNameList= new ArrayList<String>();
prgmNameList.add("bbb");
prgmNameList.add("bbb");
prgmNameList.add("ccc");
prgmNameList.remove("bbb"); //Removes by object resolved by equals() method
prgmNameList.remove(2); //Removes by index
You have created an Array which can not grow as it's fixed in size.
You need to create a list in order to add new elements as shown below.
List<String> prgmNameList = new ArrayList<String>();
prgmNameList.add("aaaa");
prgmNameList.add("bbbb");
prgmNameList.add("cccc");
You have to use ArrayList like that
ArrayList<String> al = new ArrayList<>();
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
if you want to use array as you did you have to know the number of elements that you want to add
String[] myList = new String[10];
and then
myList[4]="AA"
--
this is not possible to add to myList.
I explain you how ArrayList works and then you will understand.
ArrayList is an class that contains Array from objects. every time you add it check if it have place to store the data in the array if not it creates new array bigger and store the data.
So ArrayList this is the solution (or any other list)
if you want to add to myList you will have to implement arratList..
The method you are looking for is defined for a Collection, but you are using an array with an array initializer.
I suggest switching to the List:
public static List<String> prgmNameList= new ArrayList<>(Arrays.asList("bbbbb","aaaaa"))
Then you can call add on it because now it is a list.
Btw.: Try to prevent having mutable variables in static variables.

From Arraylist to Array

I want to know if it is safe/advisable to convert from ArrayList to Array?
I have a text file with each line a string:
1236
1233
4566
4568
....
I want to read them into array list and then i convert it to Array. Is it advisable/legal to do that?
thanks
Yes it is safe to convert an ArrayList to an Array. Whether it is a good idea depends on your intended use. Do you need the operations that ArrayList provides? If so, keep it an ArrayList. Else convert away!
ArrayList<Integer> foo = new ArrayList<Integer>();
foo.add(1);
foo.add(1);
foo.add(2);
foo.add(3);
foo.add(5);
Integer[] bar = foo.toArray(new Integer[foo.size()]);
System.out.println("bar.length = " + bar.length);
outputs
bar.length = 5
This is the best way (IMHO).
List<String> myArrayList = new ArrayList<String>();
//.....
String[] myArray = myArrayList.toArray(new String[myArrayList.size()]);
This code works also:
String[] myArray = myArrayList.toArray(new String[0]);
But it less effective: the string array is created twice: first time zero-length array is created, then the real-size array is created, filled and returned. So, if since you know the needed size (from list.size()) you should create array that is big enough to put all elements. In this case it is not re-allocated.
ArrayList<String> myArrayList = new ArrayList<String>();
...
String[] myArray = myArrayList.toArray(new String[0]);
Whether it's a "good idea" would really be dependent on your use case.
assuming v is a ArrayList:
String[] x = (String[]) v.toArray(new String[0]);
There are two styles to convert a collection to an array: either using a pre-sized array (like c.toArray(new String[c.size()])) or using an empty array (like c.toArray(new String[0])).
In older Java versions using pre-sized array was recommended, as the reflection call which is necessary to create an array of proper size was quite slow. However since late updates of OpenJDK 6 this call was intrinsified, making the performance of the empty array version the same and sometimes even better, compared to the pre-sized version. Also passing pre-sized array is dangerous for a concurrent or synchronized collection as a data race is possible between the size and toArray call which may result in extra nulls at the end of the array, if the collection was concurrently shrunk during the operation.
You can follow the uniform style: either using an empty array (which is recommended in modern Java) or using a pre-sized array (which might be faster in older Java versions or non-HotSpot based JVMs).
This is the recommended usage for newer Java ( >Java 6)
String[] myArray = myArrayList.toArray(new String[0]);
In older Java versions using pre-sized array was recommended, as the
reflection call which is necessary to create an array of proper size
was quite slow. However since late updates of OpenJDK 6 this call was
intrinsified, making the performance of the empty array version the
same and sometimes even better, compared to the pre-sized version.
Also passing pre-sized array is dangerous for a concurrent or
synchronized collection as a data race is possible between the size
and toArray call which may result in extra nulls at the end of the
array, if the collection was concurrently shrunk during the operation.
This inspection allows to follow the uniform style: either using an
empty array (which is recommended in modern Java) or using a pre-sized
array (which might be faster in older Java versions or non-HotSpot
based JVMs).
Most answers work as accepted. But since Java 11, there's another way to use toArray() method using method reference operator or double colon operation (::).
Here's an example:
ArrayList<String> list = new ArrayList<>();
// ... add strings to list
// Since java 11
String[] strArray = list.toArray(String[]::new);
// before java 11, as specified in the official documentation.
strArray = list.toArray(new String[0]);
The Collection interface includes the toArray() method to convert a new collection into an array. There are two forms of this method. The no argument version will return the elements of the collection in an Object array: public Object[ ] toArray(). The returned array cannot cast to any other data type. This is the simplest version. The second version requires you to pass in the data type of the array you’d like to return: public Object [ ] toArray(Object type[ ]).
public static void main(String[] args) {
List<String> l=new ArrayList<String>();
l.add("A");
l.add("B");
l.add("C");
Object arr[]=l.toArray();
for(Object a:arr)
{
String str=(String)a;
System.out.println(str);
}
}
for reference, refer this link http://techno-terminal.blogspot.in/2015/11/how-to-obtain-array-from-arraylist.html
One approach would be to add the Second for Loop where the printing is being done inside the first for loop. Like this:
static String[] SENTENCE;
public static void main(String []args) throws Exception{
Scanner sentence = new Scanner(new File("assets/blah.txt"));
ArrayList<String> sentenceList = new ArrayList<String>();
while (sentence.hasNextLine())
{
sentenceList.add(sentence.nextLine());
}
sentence.close();
String[] sentenceArray = sentenceList.toArray(new String[sentenceList.size()]);
// System.out.println(sentenceArray.length);
for (int r=0;r<sentenceArray.length;r++)
{
SENTENCE = sentenceArray[r].split("(?<=[.!?])\\s*"); //split sentences and store in array
for (int i=0;i<SENTENCE.length;i++)
{
System.out.println("Sentence " + (i+1) + ": " + SENTENCE[i]);
}
}
}
ArrayList<String> a = new ArrayList<String>();
a.add( "test" );
#SuppressWarnings( "unused")
Object[] array = a.toArray();
It depends on what you want to achieve if you need to manipulate the array later it would cost more effort than keeping the string in the ArrayList. You have also random access with an ArrayList by list.get( index );
I usually use this method.
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
int[] arr = list.stream().mapToInt(i -> i).toArray();
System.out.println(Arrays.toString(arr)); // [1, 2, 3]
}

Categories