This question already has answers here:
Convert an array of primitive longs into a List of Longs
(17 answers)
Closed 5 years ago.
I have an array int[] a = {1,2,3} I want to convert it to an ArrayList, and vice versa. These are my attempts but they don't work. Can someone point me in the right direction, please.
The following are my attempts below
public class ALToArray_ArrayToAL {
public static void main(String[] args) {
ALToArray_ArrayToAL obj = new ALToArray_ArrayToAL();
obj.populateALUsingArray();
}
public void populateArrayUsingAL()
{
ArrayList<Integer> al = new ArrayList<>();
al.add(1);al.add(2);al.add(3);al.add(4);
/* Don't want to do the following, is there a better way */
int[] a = new int[al.size()];
for(int i = 0;i<al.size();i++)
a[i] = al.get(i);
/* This does not work either */
int[] b = al.toArray(new int[al.size()]);
}
public void populateALUsingArray()
{
/* This does not work, and results in a compile time error */
int[] a = {1,2,3};
ArrayList<Integer> al = new ArrayList<>(Arrays.asList(a));
/* Does not work because I want an array of ints, not int[] */
int[] b = {4,5,6};
List list = new ArrayList(Arrays.asList(b));
for(int i = 0;i<list.size();i++)
System.out.print(list.get(i) + " ");
}
}
Accept the inevitability of a for loop:
for (int i : array) {
list.add(i);
}
...or use streams in Java 8, though frankly they're more of a pain than they're worth for this case:
Arrays.stream(array).boxed().collect(Collectors.toList())
...or use a third-party library like Guava and write
List<Integer> list = Ints.asList(array);
Related
This question already has answers here:
Are arrays passed by value or passed by reference in Java? [duplicate]
(7 answers)
Closed 3 years ago.
The result you are suppose to get is 0, but I don't understand why? The array is changed when its passed through other method.
public class Tester {
public static int function1 (int [] arr) {
arr= function2(arr);
return arr[0];
}
public static int[] function2 (int [] arr) {
arr = new int[4];
return arr;
}
public static void main(String[] args) {
int arr[] = {1,2,3,4};
System.out.print(Tester.function1(arr));
}
}
I expected 4 from the printed answer.
You are creating a completely new array in function2. That's why by default it is storing 0 at every index. When you are returning, the new array is returning only. For every index it will print 0 only.
Why are you creating new array in function 2? If you have to print 4 then simply pass the existing array only and print the arr[3].
Here is the code :-
public class Tester {
public static int function1 (int [] arr) {
arr= function2(arr);
//return arr[0];
return arr[3];
}
public static int[] function2 (int [] arr) {
//arr = new int[4];
return arr;
}
public static void main(String[] args) {
int arr[] = {1,2,3,4};
System.out.print(Tester.function1(arr));
}
}
This question already has answers here:
When do you use varargs in Java?
(8 answers)
Closed 4 years ago.
I could use help/direction on how to build a constructor that receives (for example 1, 2, 3) int's and stores them into an array object called arr2.
Part I:
public static void main (String[] args) {
Create an Arrays object using the first constructor
Arrays arr1 = new Arrays(5);
Arrays arr2 = new Arrays (1,2,3);
}
Part II:
public class Arrays {
private int [] array;
private int count;
public Arrays(int[] arr){
int[] array = arr;
array= arr;
count = arr.length;
}}
You could do it like this:
public class Arrays {
private int [] array;
public Arrays(int... arr){
array = arr.clone();
}
public int get(int index) {
return array[index];
}
}
Changes from your code:
The constructor uses varargs (look it up).
There is no need to store the count; if you want the count the count, use array.length().
The array is copied. This means you can change the original array that you passed in, but the values in the Arrays object won't be affected.
I've added a getter method.
Try use this constructor with var args
public Arrays(int... arr) {
int[] array = arr;
array= arr;
count = arr.length;
}
This question already has answers here:
How to convert an ArrayList containing Integers to primitive int array?
(19 answers)
Closed 7 years ago.
Does anyone know how to pass a double arraylist into another method? (I have highlighted it)I get this message from compiler : cannot convert from ArrayList to double[]
ArrayList<Double> value = new ArrayList<Double>();
while (rs.next())
{
ArrayList<Integer> r=new ArrayList<Integer>();
r.add(rs.getInt("Type"));
r.add(rs.getInt("Budget"));
r.add(rs.getInt("Day"));
r.add(rs.getInt("Preferences"));
int vec2[] = r.stream().mapToInt(t -> t).toArray();
double cos_sim=cosine_similarity(vec1,vec2);
value.add(cos_sim);
}
pick_highest_value_here_and_display(value);
ps.close();
rs.close();
conn.close();
}
private void pick_highest_value_here_and_display(ArrayList<Double> value) {
// TODO Auto-generated method stub
**double aa[]=value ;**
double highest=aa[0];
for(int i=0;i<aa.length;i++)
{
if(aa[i]>highest){
highest=aa[i];
}
}
System.out.println(highest);
}
You can use Java8 in a same way you used it for int[]
ArrayList<Double> value = new ArrayList<Double>();
double[] arr = value.stream().mapToDouble(v -> v.doubleValue()).toArray();
OR (As per below comment of yshavit)
double[] arr = value.stream().mapToDouble(Double::doubleValue).toArray();
You can copy all the element to a double[] by copying one at a time, but you don't need to.
List<Double> value = Arrays.asList(1.1, 3.3, 2.2);
Optional<Double> max = value.stream().max(Comparator.<Double>naturalOrder());
System.out.println(max.get());
prints
3.3
If you can change to Double[] then you can do like :-
Double[] doubleArr= value.toArray(new Double[value.size()]);
Else if you want double[], then you can do like :-
double[] doubleArr= new double[value.size()];
int index = 0;
for(double i : value){
doubleArr[index] = i; // unboxing is automtically done here
index++;
}
Here is a working solution:
ArrayList<Double> a = new ArrayList<Double>();
a.add(0.23);
a.add(2.4);
Double[] b = new Double[a.size()];
b = a.toArray(b);
for (int i = 0; i < b.length; i++) {
System.out.println(b[i]);
}
This question already has answers here:
Cartesian product of an arbitrary number of sets
(11 answers)
Closed 8 years ago.
I have an array that contains 3 arrays, like this:
String[][] S = { {a,b,c} , {d,e}, {f,g,h} }
Now I want to create all arrays
R = {r1,r2,r3}
where r1 belongs to S1, r2 belongs to S2, r3 belongs to S3 (S1, S2, S3 are sub-array of S) and I want have the output like that:
R1 = {S[1][1], S[2][1], S[3][1]},
R2 = {S[1][1], S[2][1], S[3][2]},
R3 = {S[1][1], S[2][1], S[3][3]},
...,
R18 = {S[1][3], S[2][2], S[3][3]}
I can not use 3 for-iterators because the array S is dynamic.
Here is a solution using recursion.
private static void fillArray(List<String> prefix, String[][] s, List<String[]> allResults){
if(prefix.size() < s.length) {
String[] currentArray = s[prefix.size()];
for (String currentString : currentArray) {
LinkedList<String> copy = new LinkedList<>(prefix);
copy.add(currentString);
fillArray(copy,s,allResults);
}
} else {
allResults.add(prefix.toArray(new String[prefix.size()]));
}
}
To use it call:
String[][] S = { {"a","b","c"} , {"d","e"}, {"f","g","h"} };
List<String[]> allResults = new LinkedList<>();
fillArray(new LinkedList<String>(),S,allResults);
for (String[] result: allResults) {
System.out.println(Arrays.toString(result));
}
EDIT:
Here is a method for what you want:
private static void fillArray2(List<String> prefix, String[][] s, List<String[]> allResults){
if(prefix.size() < s.length) {
String[] currentArray = s[prefix.size()];
for(int i=0;i<currentArray.length;i++) {
LinkedList<String> copy = new LinkedList<>(prefix);
copy.add("S["+(prefix.size()+1)+"]["+(i+1)+"]");
fillArray2(copy,s,allResults);
}
} else {
allResults.add(prefix.toArray(new String[prefix.size()]));
}
}
This question already has answers here:
How to convert an ArrayList containing Integers to primitive int array?
(19 answers)
Closed 9 years ago.
This is my second program in Java, and its the first time I'm using an arrayList.
I searched about how to convert it, and used the methods i found, but I get an error...
package eliminarepetidos;
import java.util.ArrayList;
import java.util.Random;
public class Eliminarepetidos {
public static ArrayList<Integer> eliminaRepetidos (int[] vet){
ArrayList<Integer> retorna = new ArrayList<>();
for(int i = 0; i<vet.length; i++){
for (int j = i + 1; j < vet.length; j++)
if ((vet[i] == vet[j])&&(vet[i]!=0)) vet[j]=0;
if(vet[i]!=0) retorna.add(vet[i]); }
return retorna;
}
public static void imprime (int[] vet, int numElem){
System.out.print("Vetor resultante:");
for (int i = 0;i<numElem;i++)
System.out.print(" " +vet[i]);
}
public static void main(String[] args) {
int[] t;
t = new int[10];
Random generator = new Random();
for(int i = 0; i<10; i++)
t[i] = generator.nextInt(12) +9;
ArrayList<Integer> temporario = new ArrayList<>();
temporario = eliminaRepetidos(t);
int [] vetfinal = temporario.toArray(new int[temporario.size()]); //line with error
imprime(vetfinal,vetfinal.length);
}
}
How should I be using the command to make it work properly?
Thanks!
Any ArrayList can be converted to a simple array using toArray(<Type> t) (ArrayList<Thing> list -> Thing[] arr = list.toArray(new Thing[0])), but that's likely not your real question.
Your real question, based on the code you've shown, is far more likely: "how do I iterate over an arraylist?", to which the answer is: "the same as for arrays or any other collection, use the for loop in its foreach pattern":
int[] numbers = {...}
ArrayList<Thing> things = new ArrayList<Thing>();
thing.add(new Thing(...));
...
for(int i: numbers) {
System.out.println(i); // will print each element in the array
}
for(Thing t: things) {
System.out.println(t); // will print each element in the arraylist
}
This use of the for loop has been part of plain Java since v1.5 =)