Convert an arraylist to array - java

I have an Arraylist that I want to convert it into an array. I am using this:
double[] array = new double[list.size()];
double [] array = list.toArray(new double[list.size()]);
but, it does not work. Any idea how I can fix it? Thanks in advance.
It seems it returns object.

For converting a List<Double> to a double[], or anything where you need the primitive type, there's no alternative to doing a traditional for loop (or calling a third-party library method that does a traditional for loop, such as Guava's Doubles.toArray).
double[] array = new double[list.size()];
for (int i = 0; i < list.size(); i++) {
array[i] = list.get(i);
}
Alternately, you could do
Double[] array = list.toArray(new Double[list.size()]);
which would get you the array of boxed Doubles, which might suffice for your purposes anyway.

A List can't contain primitive types. Assuming it contains instances of Double, the only way is to iterate over the list and unbox each element (hoping there's no null in the list):
double[] array = new double[list.size()];
int i = 0;
for (Double d : list) {
array[i] = d;
i++;
}

Please read the java docs:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html
HTH.

Use the Object Double not the primitive double:
ArrayList<Double> list = new ArrayList<Double>();
...add data
Double[] array=list.toArray(new Double[list.size()]);

It should be:
Double[] array = new Double[list.size()];
list.toArray(array); // fill the array
and if you want an array of primitives, iterate over each element in the array:
double[] array = new double[list.size()];
for(int i = 0; i < list.size(); i++) array[i] = list.get(i).doubleValue();

StringBuffer strBuffer = new StringBuffer();
for(Object o:list){
strBuffer.append(o);
}
double []x = new double[]{strBuffer.toString()};
I consider this should work

Related

Array or ArrayList?

Here is an exercise:
Write an algorithm that declares and fills an array of 7 values numerics, bij putting the values to 0.
In Python I have to do this:
note = []
for i in range(7):
note.append(0)
print( note )
I have tried below in Java... I am obliged to use an arrayList?
I would like the do with an array empty.
int[] notes;
for(int i=0;i<7;i++){
notes.add(0);
}
try this:
int[] notes = new int[7];
for(int i=0;i<7;i++){
notes[i] = 0;
}
When declaring your notes array you must initialize it and specify the length of it. If not it will throw a compilation error. Proceed as follows:
int[] notes = new int[7]; //Declare the size of the array as 7
for(int i=0;i<7;i++){
notes[i] = 0; //Iterate the positions of the array via the variable i.
}
If you want to use an ArrayList:
List<Integer> notes = new ArrayList<Integer>(); //You don't have to define the length.
for(int i = 0; i < 7, i++) {
notes.add(0);
}
You can also do like this.
Arrays.fill(notes, -1);// But notes has to be declared.
or
int[] notes = {0,0,0};
For the special case of int and a desired value of 0, you don't even have to write out the loop assignment. You just need this:
int[] notes = new int[7];
This will create an array of ints, each with the Java default value of 0.
You need to use an assignment operation.
notes[i] = 0;
Another option - using streams:
int[] notes = IntStream.range(0, 7).map(i -> 0).toArray();
But if you need exactly 0, you can simply do it like:
int[] notes = new int[7]; // but it for 0 only

array of arraylist type error

void radix(int[] arr, int maxDigit){
int exp = 1;
for (int i=0; i<maxDigit; i++) {
ArrayList[] bucket = new ArrayList[10];
for (int n=0; n<10; n++){
bucket[n] = new ArrayList<Integer>();
}
for (int j=0; j<arr.length; j++){
bucket[(arr[j]%exp)%10].add(arr[j]);
}
int ind=0;
for (int k=0; k<10; k++){
for (int n : bucket[k]){
arr[ind] = n;
ind++;
}
}
exp*=10;
}
}
above is my attempt for a radix sort in java.
I keep having an error at this for loop:
for (int n : bucket[k])
Saying that Object can't be converted to int.
However, I declared the array to have an arrayList as its element,
so bucket[k] should be an arraylist.
Can anyone please explain why this happens and how I could get around this problem?
I would appreciate any help. Thanks
You have an ArrayList<Integer>. Try using for(Integer n : bucket[k])
You also need to provide a type for ArrayList. Try ArrayList<Integer>[] bucket = new ArrayList[10];
ArrayList[] bucket = new ArrayList[10];
This does not have the type parameter.
And you should avoid using inflexible, low-level constructs like arrays anyways.
Try to actually express your intents in your code with identifiers and to use first-class objects for all of your key concepts.
You have an ArrayList not ArrayList.
Change:
for(int n : bucket[k])
To:
for(Integer n : bucket[k])
You also need to type your ArrayList declaration with:
ArrayList<Integer>[] bucket = new ArrayList<Integer>[];

Array in Java, how to populate

Hi i'd like to populate array in Java. I'm trying to do it on easily way
int[] tab = null;
for(int i=0; i<5; i++)
{
tab[i]=i;
}
Why this constructions not working ?
error: null pointer exception
This is how you implement it
int[] tab = new int[5];
for(int i=0; i<tab.length; i++)
{
tab[i]=i;
}
Dynamic allocation means you should be using one of the Collection instances, such as a List. If you have some constraint (such as homework rules) that says you must use an array, then you have to do the following:
declare and instantiate the array to some arbitrary size: int[] intArray = new int[20];
during the addition of the elements, check if the index is equal to the length - 1: if(index == length - 1) , and if true,
create a temporary array of a size that is some multiple of the original array's size (usually 2x) int[] temp = new int[intArray.length*2];
copy the elements from the original array to the temp array
reassign the temp variable value to the original: intArray = temp;
after the loop, create a new array that is the correct length and copy all values from the original to the new one. (this is because the size will most certainly be wrong -- the length will be more than the number of elements).
In pseudo code, it looks like this:
int[] intArray = new int[20];
int index = 0;
loop:
if(index >= intArray.length - 1){
int[] temp = new int[intArray.length * 2];
copyAll: intArray->temp // use System.arrayCopy
intArray = temp;
}
intArray[index] = value;
index++;
endloop:
// resize because intArray will likely be too big
int[] temp = new int[index];
copyAll intArray -> temp;
intArray = temp;
As you can see, it's much, much nicer to use the Collection framework:
List<Integer> intList = new ArrayList<Integer>();
loop:
intList.add(value);
endloop
Here is how I would implement this array in the simplest way possible:
int[] tab = new int[]{0, 1, 2, 3, 4};
Your code doesn't work because you never create a new object to hold the elements of the array, it just creates space for a reference to that object. Before you can reference the object using
tab[i]
you must create a new object like this:
tab = new int[5];
So, if you really want to implement this variable in a for loop for whatever reason, here's how you should do it:
final int ARRAY_SIZE = 5;
int[] tab = new int[ARRAY_SIZE];
for(int i=0; i<ARRAY_SIZE; i++){
tab[i] = i;
}
Now, if you want to increase the number of elements in your array, you just need to change the ARRAY_SIZE variable.
You need to initialize your array before you use it:
int[] tab = new int`[5];
If you need something that is dynamicaly allocated use something like Vector or ArrayList:
For example:
ArrayList<Integer> list = new ArrayList<Integer>();
int elements_to_add = 5;
for(int i=0; i<elements_to_add; i++)
{
list.add(new Integer(i) );
}
Despite the fact that you declare this array and pass it null, you don't create any object here. You have only a reference to null. That's the reason of your error. What you have to do is initialize this array like int []myArray = new int[5];
Something like this should work :
int[] tab = new int[5];
for(int i=0; i<5; i++){
tab[i] = i;
}

Array of arraylists

im having trouble making an array of arraylists, heres's the code : 'ArrayList<Integer>[] solucao= new ArrayList[6];'
and using this code below:
solucao[0].add(1);
solucao[0].size();
solucao[1].size();
solucao[1].add(1);
solucao[2].size();
solucao[2].add(1);
solucao[3].size();
solucao[3].add(1);
solucao[4].size();
solucao[4].add(1);
solucao[5].size();
solucao[5].add(1);
solucao[6].size();
solucao[6].add(1);
solucao[7].size();
solucao[7].add(1);
all the calls for size return null. Anyone knows how to solve it?
Im looking for a data structure of array of arraylists, as each array[i] position will return me an arraylist of integers.
thank you
You have to initialize each ArrayList in the array.
ArrayList[] solucao = new ArrayList[6];
for (int i = 0; i < solucao.length; i++)
solucao[i] = new ArrayList();
I actually thought you couldn't have an array of ArrayList. Apparently you can, but it must be non-generic. You should probably reconsider why you're doing this...
Arrays are just pointers or references. For each for them you have to create a new ArrayList object and store your data in it.
List[] solucao= new ArrayList[5];
for(int i=0;i<solucao.length;i++)
{
solucao[i] = new ArrayList();
solucao[i].add(yourObject);
}
ArrayList<Integer>[] solucao= new ArrayList[6];
Should be new ArrayList<Integer>[6]
Note an IDE would give you a warning about this. Next, initialize each element of the array (Java 7):
for(int i = 0; i < solucao.length; i++) {
solucao[i] = new ArrayList<>();
For store data first you have to create object.
ArrayList<Integer>[] ls = new ArrayList[7];
for (int i = 0; i < ls.length; i++) {
ls[i] = new ArrayList<Integer>();
for(int j = 0 ; j<i ;j++){
ls[i].add(j);
}
System.out.println(ls[i].size());
}

add values in a array list

I have the following ArrayList
ArrayList<double[]> db_results = new ArrayList<double[]>();
Which is populated by the following loop
double[] nums = new double[3];
for ( int i = 0 ; i <= 2; i++) {
double val = Double.parseDouble(i);
nums[i] = val;
}
db_results.add(nums);
How can i add the values from the same position in each array to make another array??
So 1+1+1=3 would be position one of the new array 2+2+2=6 would be position two of the new array and 3+3+3=9 would be position three of the new array??
Cheers
A nested loop would do it.
I would encourage you to take the time to do a Java tutorial or read a textbook. This is really basic stuff, and you'd do better learning the language properly than learning by trial and error interspersed with random SO questions.
By the way, this line from your code won't compile:
double val = Double.parseDouble(i);
The i variable is declared as an int and the parseXxx methods take a String argument. To convert an int to double, just assign it:
double val = i;
This might be what you're looking for:
double[] newArray = new double[3];
for (double[] array : db_results) {
for (int i = 0; i < 3; ++i) {
newArray[i] += array[i];
}
}
It will work after db_results has been populated. You can also compute the sum array at the same time that db_results is being populated using slukian's method.
Either a java math function or a nested loop its for your answer. Try yourself its just a mathematical calculation.

Categories