Questions about ArrayList - java

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.

Related

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

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

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();

How to create an array of vector in Java?

So, I want an array of Vector of Integer in Java.
If I put
Vector<Integer>[] matrix;
matrix = new Vector<Integer>[100];
I get cannot the compilation error
cannot create a generic array of Vector
Should I use
matrix = new Vector[100];
instead? (which gives a warning)
Or should I simply not use an array of vectors and use vector of vector instead?
Note: I don't want a Vector< Integer >, I want a Vector< Integer >[] to create a matrix of Integers without using Integer[][].
Java simply doesn't have any means to create arrays of a parameterized type without getting or suppressing a warning. So the best you can get is this:
#SuppressWarnings("unchecked")
Vector<Integer>[] anArray = (Vector<Integer>[]) new Vector<Integer>[100];
You can get around this problem if you avoid arrays entirely. I.e.:
Vector<Vector<Integer>> list = new Vector<Vector<Integer>>(100);
Or with the collection types:
List<List<Integer>> list = new ArrayList<List<Integer>>(100);
Vector<Integer> vector = new Vector<Integer>();
If you try to do something like this:
Vector<Integer> vector = new Vector<Integer>();
Vector<Integer>[] vectors = {vector};
You will get a compile error:
Cannot create a generic array of
Vector
However if you don't specify the generic type java will allow it but with a warning:
Vector<Integer> vector = new Vector<Integer>();
Vector[] vectors = {vector};
Vectors are backed by arrays, and will grow or shrink to a size sufficent to hold the element you insert into it. As such, you can pre-allocate a Vector, but you do not have to actually specify the size at create time.
// preallocated vector, which can hold 100 elements
Vector<Integer> integers = new Vector(100);
.
// default vector, which will probably grow a couple of times when adding 100 element
Vector<Integer> integers = new Vector();
A true Java array cannot grow or shrink, and it doesn't support removal of an element from a mid-point. To allocate an Array, you use
// allocate an array
Integer[] integers = new Integer[100];
Now if you want to have an "array of vectors" then you would
// array of vectors
Vector[] vectors = new Vector[100];
To create an array of generic you have to create the non-generic and cast it. You also have to initialise all the elements in the array, otherwise they will be null. :(
Vector<Integer>[] anArray = (Vector<Integer>[]) new Vector[100];
for(int i = 0; i < anArray.length; i++)
anArray[i] = new Vector<Integer>();
However, since Vector is a legacy class which was replaced by ArrayList in Java 1.2 (1998) I would use List for the interface and ArrayList for the implementation.
List<Integer>[] anArray = (List<Integer>[]) new List[100];
for(int i = 0; i < anArray.length; i++)
anArray[i] = new ArrayList<Integer>();
Another option would be to use a collection which held primitive int instead of Integer Objects. This can enhance performance if you need it.
TIntArrayList[] anArray = new TIntArrayList[100];
for(int i = 0; i < anArray.length; i++)
anArray[i] = new TIntArrayList();
To avoid type casting, consider this implementation:
Vector<Integer>[] intVectorArray;
Vector[] temp = new Vector[desiredSize];
intVectorArray = temp;
for(int i = 0;i<intVectorArray.length;i++){
hashArray[i] = new Vector<Integer>();
}
The newly created intVectorArray will inherit the generic Vector-Array type of temp to give you your desired dimensions, and the for loop will instantiate your desired datatype.
When you're ready to call Integer functions on elements of intVectorArray, you will be all set!

in java can one have an array of variables?

in java can you have an array of variables?
if so what is the syntax?
here's an example if your confused:
varint[] ArrayOfVariablesThatAreInts = new varint[#]
or
var[] ArrayofVariables = new var[#]
is something like this legal?
Yes you can use:
Foo[] arrFoo = new Foo[10];
arrFoo[0] = new Foo();
..
Or if you dont want to define a fix size, you can use an ArrayList:
List<Foo> arrFoos = new ArrayList<Foo>();
arrFoos.add(new Foo());
..
To create an array of ints for example you would use:
int[] array = new int[size];
Where size is how big you want the array to be.
Sure. You can do something like:
String[] arrayOfStrings = new String[10];
Not really.
You can have an array of int values though:
int[] intArray = new int[100]; // array to hold 100 int's
But you can't use them as variables, you'll have to use them as values.
intArray[0] = 512;// set's the first element in the array to 512
int someIntVariable = intArray[0]; // get the first element in the array ( 512 ) .
Arrays are fixed size ( once allocated can't shrink or grow ) to do that you should use a List ( variable size ) of ints:
List<Integer> list = new ArrayList<Integer>(); // Integer is a wrapper for int
list.add(512);
list.add(1024);
int x = list.get(0);// get the first element in the list ( 512 )
I'm not sure if this is what you mean by a array of variables but see if this is what your looking for.
import java.util.ArrayList;
public class StackQuestion {
private static int random1 = 1;
private static int random2 = 2;
public static void main(String [] args){
ArrayList a1 = new ArrayList();
a1.add(random1);
a1.add(random2);
System.out.println(a1.get(0));
System.out.println(a1.get(1));
}
}
In java you can have arrays of a specific type (like string, int or any object). You can use this array positions to store variables if you want to store them in an array. Or alternatively you can create an object array which can store variables of different types.
The length of the array needs to be pre defined and if that doesn't suit you,you can use any cooleciton like ArrayList

Categories