Convert ArrayList to Int [] array using .toArray()? Or...? - java

So, this is part of a method which checks for available rooms within a date range and is meant to return the int [] array of room numbers which are available.
ArrayList roomNums = new ArrayList();
roomNums.toArray();
for (Room room: rooms){
int roomNumber = room.getRoomNumber();
if(room.getRoomType() == roomType && isAvailable(roomNumber, checkin, checkout)){ // This works fine, ignore it
roomNums.add(roomNumber);
}
}
return roomNums.toArray(); // Error here, return meant to be int [] type but it's java.lang.Obeject []
The error occurs at the end at roomNums.toArray()
I saw someone else do this one liner and it worked for them, why is it not for me?
Every element in roomNums is an integer. (I think)
What's the quickest and easiest way to print an integer array containing the available rooms? Do I need to make a loop or can I do something with this .toArray() one liner or something similar to it?
Thanks

Don't use raw types. Replace ArrayList roomNums = new ArrayList(); with
ArrayList<Integer> roomNums = new ArrayList<>();
Then return it as Integer[]
roomNums.toArray(Integer[]::new);
If you need primitive array, then it can be done with stream:
return roomNums.stream().mapToInt(Integer::valueOf).toArray();
See also How to convert an ArrayList containing Integers to primitive int array?

Unfortunately, you will need to use Integer[] if you want to use toArray
List<Integer> roomNums = new ArrayList<>();
// code here
Integer[] arr = new Integer[roomNums.size()];
return roomNums.toArray (arr);
However you can still do it manually like
List<Integer> roomNums = new ArrayList<> ();
// code here
int[] arr = new int[roomNums.size()];
for (int i = 0; i < arr.length; i++)
arr[i] = roomNums.get (i);
return arr;

As mentioned above use the ArrayList to hold your values:
ArrayList<Integer> roomNums = new ArrayList<>();
then you can use the object super class to convert to array
Object[] numbersArray = roomNums.toArray();
then just continue running the for loop and your program

Related

Questions about ArrayList

I need to use an ArrayList, but I am not sure how to do some of these things that would be possible with a normal array.
1) This:
int[][] example1 = new int[10][20];
(An array with two arguments (10, 20)) is possible with normal arrays, but how to do it with an ArrayList.)
2) How to increase the value of an int on the list by 1, like this:
example2[3][4] ++;
ArrayList is dynamically growable list backed by array.
List<List<Integer>> list = new ArrayList<List<>>(10);
you can get an element of list by List#get.
List<Integer> innerList = list.get(3);
Integer integer = innerList.get(4);
Update value by List#set -
list.get(3).set(4,list.get(3).get(4)++);
NOTE : Integer class is immutable.
To mimic a multidimensional array using collections you would use:
List<List<Integer>> list = new ArrayList<>(); //Java 7
List<List<Integer>> list = new ArrayList<List<Integer>>(); //Pre Java 7
So lets say we create a List<List<Integer>> where the outer List contains 10 List<Integer> and the inner list contains 10 Integers. To set the fifth element on the fourth list:
public static void main(String[] args) {
List<List<Integer>> outer = new ArrayList<List<Integer>>();
for(int x = 0; x < 10; x++){
List<Integer> inner = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
outer.add(inner);
}
//Remember that Integer is immutable
outer.get(3).set(4, new Integer(outer.get(3).get(4)) + 1);
}
int[][] example1 = new int[10][20]; you can do it in arraylist by using this syntax :
ArrayList<ArrayList<Integer>> ex = new ArrayList<ArrayList<Integer>>();
example2[3][4] ++; This can be same in arraylist as by using this :
int val = (a.get(0).get(0)) + 1;
The equivalent of your declaration with an ArrayList is:
List<List<Integer>> example1 = new ArrayList<>();
You have to use Integer because Java Collections do not support primitive types. Check out this page of the Oracle docs for more information on Autoboxing and Unboxing.
Since an ArrayListcan grow dynamically, you don't need to give a size. If you want it to have an initial size, you can pass that as an argument to the constructor.
You can get elements from an ArrayList (or any Class implementing the List interface) by using the get() method with the index of the element as an argument.
Using example.get() on example1 will give you an object of the type List. You can then use get() again to get an Integer.

Java ArrayList for integers

I have values that I'd like to add into an ArrayList to keep track of what numbers have shown up.
The values are integers so I created an ArrayList;
ArrayList<Integer[]> list = new ArrayList<>();
int x = 5
list.add(x);
But I'm unable to add anything to the ArrayList using this method.
It works if I use Strings for the array list. Would I have to make it a String array and then somehow convert the array to integers?
EDIT: I have another question. I'd like the list to only hold 3 values. How would I do so?
List of Integer.
List<Integer> list = new ArrayList<>();
int x = 5;
list.add(x);
You are trying to add an integer into an ArrayList that takes an array of integers Integer[]. It should be
ArrayList<Integer> list = new ArrayList<>();
or better
List<Integer> list = new ArrayList<>();
you are not creating an arraylist for integers, but you are trying to create an arraylist for arrays of integers.
so if you want your code to work just put.
List<Integer> list = new ArrayList<>();
int x = 5;
list.add(x);
you should not use Integer[] array inside the list as arraylist itself is a kind of array. Just leave the [] and it should work
Actually what u did is also not wrong your declaration is right . With your declaration JVM will create a ArrayList of integer arrays i.e each entry in arraylist correspond to an integer array hence your add function should pass a integer array as a parameter.
For Ex:
list.add(new Integer[3]);
In this way first entry of ArrayList is an integer array which can hold at max 3 values.
The [] makes no sense in the moment of making an ArrayList of Integers because I imagine you just want to add Integer values.
Just use
List<Integer> list = new ArrayList<>();
to create the ArrayList and it will work.
Here there are two different concepts that are merged togather in your question.
First : Add Integer array into List. Code is as follows.
List<Integer[]> list = new ArrayList<>();
Integer[] intArray1 = new Integer[] {2, 4};
Integer[] intArray2 = new Integer[] {2, 5};
Integer[] intArray3 = new Integer[] {3, 3};
Collections.addAll(list, intArray1, intArray2, intArray3);
Second : Add integer value in list.
List<Integer> list = new ArrayList<>();
int x = 5
list.add(x);
How about creating an ArrayList of a set amount of Integers?
The below method returns an ArrayList of a set amount of Integers.
public static ArrayList<Integer> createRandomList(int sizeParameter)
{
// An ArrayList that method returns
ArrayList<Integer> setIntegerList = new ArrayList<Integer>(sizeParameter);
// Random Object helper
Random randomHelper = new Random();
for (int x = 0; x < sizeParameter; x++)
{
setIntegerList.add(randomHelper.nextInt());
} // End of the for loop
return setIntegerList;
}

Convert list to array in Java [duplicate]

This question already has answers here:
Converting 'ArrayList<String> to 'String[]' in Java
(17 answers)
Closed 4 years ago.
How can I convert a List to an Array in Java?
Check the code below:
ArrayList<Tienda> tiendas;
List<Tienda> tiendasList;
tiendas = new ArrayList<Tienda>();
Resources res = this.getBaseContext().getResources();
XMLParser saxparser = new XMLParser(marca,res);
tiendasList = saxparser.parse(marca,res);
tiendas = tiendasList.toArray();
this.adaptador = new adaptadorMarca(this, R.layout.filamarca, tiendas);
setListAdapter(this.adaptador);
I need to populate the array tiendas with the values of tiendasList.
Either:
Foo[] array = list.toArray(new Foo[0]);
or:
Foo[] array = new Foo[list.size()];
list.toArray(array); // fill the array
Note that this works only for arrays of reference types. For arrays of primitive types, use the traditional way:
List<Integer> list = ...;
int[] array = new int[list.size()];
for(int i = 0; i < list.size(); i++) array[i] = list.get(i);
Update:
It is recommended now to use list.toArray(new Foo[0]);, not list.toArray(new Foo[list.size()]);.
From JetBrains Intellij Idea inspection:
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. 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).
An alternative in Java 8:
String[] strings = list.stream().toArray(String[]::new);
Since Java 11:
String[] strings = list.toArray(String[]::new);
I think this is the simplest way:
Foo[] array = list.toArray(new Foo[0]);
Best thing I came up without Java 8 was:
public static <T> T[] toArray(List<T> list, Class<T> objectClass) {
if (list == null) {
return null;
}
T[] listAsArray = (T[]) Array.newInstance(objectClass, list.size());
list.toArray(listAsArray);
return listAsArray;
}
If anyone has a better way to do this, please share :)
I came across this code snippet that solves it.
//Creating a sample ArrayList
List<Long> list = new ArrayList<Long>();
//Adding some long type values
list.add(100l);
list.add(200l);
list.add(300l);
//Converting the ArrayList to a Long
Long[] array = (Long[]) list.toArray(new Long[list.size()]);
//Printing the results
System.out.println(array[0] + " " + array[1] + " " + array[2]);
The conversion works as follows:
It creates a new Long array, with the size of the original list
It converts the original ArrayList to an array using the newly created one
It casts that array into a Long array (Long[]), which I appropriately named 'array'
This is works. Kind of.
public static Object[] toArray(List<?> a) {
Object[] arr = new Object[a.size()];
for (int i = 0; i < a.size(); i++)
arr[i] = a.get(i);
return arr;
}
Then the main method.
public static void main(String[] args) {
List<String> list = new ArrayList<String>() {{
add("hello");
add("world");
}};
Object[] arr = toArray(list);
System.out.println(arr[0]);
}
For ArrayList the following works:
ArrayList<Foo> list = new ArrayList<Foo>();
//... add values
Foo[] resultArray = new Foo[list.size()];
resultArray = list.toArray(resultArray);
Example taken from this page: http://www.java-examples.com/copy-all-elements-java-arraylist-object-array-example
import java.util.ArrayList;
public class CopyElementsOfArrayListToArrayExample {
public static void main(String[] args) {
//create an ArrayList object
ArrayList arrayList = new ArrayList();
//Add elements to ArrayList
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
arrayList.add("5");
/*
To copy all elements of java ArrayList object into array use
Object[] toArray() method.
*/
Object[] objArray = arrayList.toArray();
//display contents of Object array
System.out.println("ArrayList elements are copied into an Array.
Now Array Contains..");
for(int index=0; index < objArray.length ; index++)
System.out.println(objArray[index]);
}
}
/*
Output would be
ArrayList elements are copied into an Array. Now Array Contains..
1
2
3
4
5
You can use toArray() api as follows,
ArrayList<String> stringList = new ArrayList<String>();
stringList.add("ListItem1");
stringList.add("ListItem2");
String[] stringArray = new String[stringList.size()];
stringArray = stringList.toArray(stringList);
Values from the array are,
for(String value : stringList)
{
System.out.println(value);
}
This (Ondrej's answer):
Foo[] array = list.toArray(new Foo[0]);
Is the most common idiom I see. Those who are suggesting that you use the actual list size instead of "0" are misunderstanding what's happening here. The toArray call does not care about the size or contents of the given array - it only needs its type. It would have been better if it took an actual Type in which case "Foo.class" would have been a lot clearer. Yes, this idiom generates a dummy object, but including the list size just means that you generate a larger dummy object. Again, the object is not used in any way; it's only the type that's needed.
Try this:
List list = new ArrayList();
list.add("Apple");
list.add("Banana");
Object[] ol = list.toArray();

Remove a specific string from an array of string

I have an array like this:
String n[] = {"google","microsoft","apple"};
What I want to do is to remove "apple".
My problem is very basic,however,I searched the website and I found out that java doesn't really support the deleting feature from an array.I also heard to use Java Utils, because it's so simple to remove an item....I tried to find Java Utils on google, but almost all links are dead.
So finally...is there any way to remove a string from an array of string?
Even if I use an ArrayList I can't find a method to generate a random item in it! For ex: in a normal array I generate a string like this:
String r = myAL[rgenerator.nextInt(myAL.length)];
In an arraylist it doesn't work....maybe you know a solution...
Define "remove".
Arrays are fixed length and can not be resized once created. You can set an element to null to remove an object reference;
for (int i = 0; i < myStringArray.length(); i++)
{
if (myStringArray[i].equals(stringToRemove))
{
myStringArray[i] = null;
break;
}
}
or
myStringArray[indexOfStringToRemove] = null;
If you want a dynamically sized array where the object is actually removed and the list (array) size is adjusted accordingly, use an ArrayList<String>
myArrayList.remove(stringToRemove);
or
myArrayList.remove(indexOfStringToRemove);
Edit in response to OP's edit to his question and comment below
String r = myArrayList.get(rgenerator.nextInt(myArrayList.size()));
It is not possible in on step or you need to keep the reference to the array.
If you can change the reference this can help:
String[] n = new String[]{"google","microsoft","apple"};
final List<String> list = new ArrayList<String>();
Collections.addAll(list, n);
list.remove("apple");
n = list.toArray(new String[list.size()]);
I not recommend the following but if you worry about performance:
String[] n = new String[]{"google","microsoft","apple"};
final String[] n2 = new String[2];
System.arraycopy(n, 0, n2, 0, n2.length);
for (int i = 0, j = 0; i < n.length; i++)
{
if (!n[i].equals("apple"))
{
n2[j] = n[i];
j++;
}
}
I not recommend it because the code is a lot more difficult to read and maintain.
Arrays in Java aren't dynamic, like collection classes. If you want a true collection that supports dynamic addition and deletion, use ArrayList<>. If you still want to live with vanilla arrays, find the index of string, construct a new array with size one less than the original, and use System.arraycopy() to copy the elements before and after. Or write a copy loop with skip by hand, on small arrays the difference will be negligible.
You can't remove anything from an array - they're always fixed length. Once you've created an array of length 3, that array will always have length 3.
You'd be better off with a List<String>, e.g. an ArrayList<String>:
List<String> list = new ArrayList<String>();
list.add("google");
list.add("microsoft");
list.add("apple");
System.out.println(list.size()); // 3
list.remove("apple");
System.out.println(list.size()); // 2
Collections like this are generally much more flexible than working with arrays directly.
EDIT: For removal:
void removeRandomElement(List<?> list, Random random)
{
int index = random.nextInt(list.size());
list.remove(index);
}
import java.util.*;
class Array {
public static void main(String args[]) {
ArrayList al = new ArrayList();
al.add("google");
al.add("microsoft");
al.add("apple");
System.out.println(al);
//i only remove the apple//
al.remove(2);
System.out.println(al);
}
}

defining an array size without hardcoding in Java

I'm having a problem where I cannot initialize an array without hard-coding it in Java.
So this is the hard-code version which works:
int numberOfElements = inputFromFile(args[0], myArray);
int [] myArray = new int[1000];
inputFromFile is basically going to be a method I'm going to write that can read the numberOfElements from a textfile along with my program.
I tried fixing it without hardcoding and got my result to be this:
int numberOfElements = inputFromFile(args[0], myArray);
int [] myArray = new int[numberOfElements];
Problem remains that Eclipse wants me to initialize myArray which is an integer array. Is there any good fixes without hard-coding? Any suggestion would be great.
Use an ArrayList, instead? Java, like C, requires constant sized arrays.
You need to initialize an array before using. You are aware of that, i assume.
If you dont know the size of your data, ie: you wont know how big the array size will be, then you will need to use ArrayList<T> which uses array internally and manages reallocation of array size for you.
If you have to use an array, you will have to maintain the array size yourself. as the array grows, you might run out of buckets if you dont set up enough space for the data ie: IndexOutOfBoundsException etc. Then you need to create a new array copy the content of the current array and then continue. All this is done for you in ArrayList, that s the benefit. Saves you time and implementation. Moreover, there is a concept called load factor which is used to expand the array.
Load factor for array is usually:
(j * 3) / 2 + 1 // j for the current length of the array.
FYI: Copying of array becomes very expensive if you data grows very big.
int numberOfElements = inputFromFile(args[0], myArray);
int [] myArray = new int[1000];
By looking at your code, your order of statements is wrong and should be :
int [] myArray = new int[1000];
int numberOfElements = inputFromFile(args[0], myArray);
you are passing myArray to a method before declaring and initializing it.
ArrayList<Integer> s = new ArrayList<Integer>();
int numberOfElements = inputFromFile(args[0], myArray);
This would be better. Then you need to change your method signature as follows:
public void inputFromFile(String fileName, ArrayList<Integer> collection){
// your impl.
}
The various way to use and declare arrays: http://leepoint.net/notes-java/data/arrays/arrays.html
I think you are getting the error because
1) you are using myArray before it is declared.
2) return type of the function inputFromFile does not match int.
I think the following program will answer your question. Here I have a int identifier 'm' which is getting set to a value returned by the 'getNumber' method. Then I am declaring an array of size m.
public class Practise {
public static void main(String args[]){
int m = getNumber();
int [] a = new int[m];
for(int i = 0; i < m; i++)
System.out.println(a[i]);
}
public static int getNumber(){
Scanner input = new Scanner(System.in);
int i = 0;
i = input.nextInt();
return i;
}
}
You can provide the size of your array as command line argument.
Using Dependency Injection of Spring can also be a good way to go, I hope you know how to write a simple bean (constructor injection / setter injection ).
Neither of your code blocks will work, as you try to use myArray before it's declared, or else you try to redeclare myArray. Other than that, if by "hardcode" you mean use a literal value, then no, you don't have to do that. Any of these will work:
int[] arr1 = new int[5];
int size = 10;
int[] arr2 = new int[size];
int sizeLoadedFromFile = loadSizeFrom("/foo/bar/baz");
int[] arr3 = new int[sizeLoadedFromFile];
Note you can also declare an array without an explicit "size" argument if you know the elements ahead of time:
int[] arr4 = {1, 2, 3, 4};
If you think you want an array, but you don't know the size ahead of time, then what you really want is some kind of Collection--probably a List:
List<Integer> list1 = new ArrayList();
list1.add(1);
list1.add(2);
list1.add(3);
list1.add(4);
or more readably, again if you know the elements ahead of time:
List<Integer> list2 = new ArrayList() {{
add(1); add(2); add(3); add(4);
}};
or
List<Integer> list3 = Arrays.asList(1, 2, 3, 4, 5);
The Collections Tutorial should tell you anything else you need to know.
An alternative to using List<Integer> is to use the Trove4j TIntArrayList. This is effectively a wrapper for int[].
However, ArrayList<Integer> is usually fast enough for most use cases.

Categories