How fill ArrayList dynamically? - java

How can I fill an ArrayList without determining the cell numbers . In other words how can I have an ArrayList in which both input values and cell numbers are unknown.
For example I don't need to below code, I need that fill ArrayList dynamic:
ArrayList<Integer> arrlist = new ArrayList<Integer>(5);
arrlist.add(15);
arrlist.add(22);
arrlist.add(30);
arrlist.add(40);
I need add these in arrayList dynamic (Loop):
arrlist.add(15);
arrlist.add(22);
arrlist.add(30);
arrlist.add(40);

I have the feeling that you're confusing loop with dynamic, they are two different things. If you want to loop, you can do something like:
final int[] ARRAY = {15, 22, 30, 40};
ArrayList<Integer> arrlist = new ArrayList<Integer>();
for(int i=0;i<ARRAY.length;i++) {
arrlist.add(ARRAY[i]);
}
Note that you don't have to specify the initial capacity of the array list.

You can use ArrayList.add(E) - it will append an element to the array list and allocate the space for it if needed, no need to pre-allocate the desired space for the ArrayList - that's the point of Dynamic Arrays.
ArrayList<Integer> arrlist = new ArrayList<Integer>();
arrlist.add(15);
arrlist.add(22);
arrlist.add(30);
arrlist.add(40);
System.out.println(arrlist);
If you wish to use loops, you can use a for-each loop, assuming you have your elements in some other array/Iterable:
ArrayList<Integer> arrlist = new ArrayList<Integer>();
int[] elements = {15, 22, 30, 40};
for (int x : elements) {
arrlist.add(x);
}

You can istantiate an ArrayList with the command
ArrayList<Integer> list = new ArrayList <Integer> ();
Then you can add all the elements you want, and if you want to know the length of your ArrayList, you can use the size method: list.size();

Fairly easy.
ArrayList<Integer> arrlist = new ArrayList<Integer>();
Just don't enter a value when you create a new ArrayList.
You can now enter however many values you want.
EDIT: Woops, someone already answered it while i was typing

Related

Storing an ArrayList in an 2d Array Java

How can I store an ArrayList in a two dimensional array?
I've tried it like this, but it won't work:
ArrayList<Integer> arrList = new ArrayList<Integer>();
ArrayList<Integer>[][] arr = new ArrayList<Integer>[9][9];
but it won't even let me declare the ArrayList-Array.
Is there a way to store a list in a 2d array?
Thanks in advance!
You can't create arrays of generic types in Java. But this compiles:
ArrayList<Integer> arrList = new ArrayList<Integer>();
ArrayList<Integer>[][] arr = (ArrayList<Integer>[][]) new ArrayList[9][9];
arr[0][0] = arrList;
Why can't you create these arrays? According to the Generics FAQ, because of this problem:
Pair<Integer,Integer>[] intPairArr = new Pair<Integer,Integer>[10]; // illegal
Object[] objArr = intPairArr;
objArr[0] = new Pair<String,String>("",""); // should fail, but would succeed
Assuming you want an ArrayList inside an ArrayList inside yet another ArrayList, you can simply specify that in your type declaration:
ArrayList<ArrayList<ArrayList<Integer>>> foo = new ArrayList<ArrayList<ArrayList<Integer>>>();
Entries can be accessed via:
Integer myInt = foo.get(1).get(2).get(3);
Just be wary of boundaries - if you try to access an out of bounds index you'll see Exceptions thrown.

java - "int cannot be converted to ArrayList"

I'm trying to create a two dimensional ArrayList which will store ints, strings & booleans.
I've got as far as entering the first int, but I get a red squiggle and the error "int cannot be converted to ArrayList".
ArrayList[][] qarray= new ArrayList [10][5];
qarray[0][0]= 1;
BTW, googling the phrase "int cannot be converted to ArrayList" is giving me exactly six results.
The error is correct.
Your array type is ArrayList. You can insert only ArrayLists in that array.
If you want to store int's, your declaration should be.
int[][] qarray= new int [10][5];
And also, as someone commented, you cannot store strings and booleans in this array anymore.
ArrayList[][] qarray= new ArrayList [10][5];
Basically your code creates 2 dimensional array list objects (50 array list objects).
qarray[0][0]= 1;
And you are trying to assign integer, where you need to create a ArrayList object. It expects something like
qarray[0][0]= new ArrayList();
However this would not meet your objective. The following piece of code could meet your objectives:
ArrayList[] qarray = new ArrayList[10];
qarray[0]= new ArrayList();
qarray[0].add(1);
qarray[1]= new ArrayList();
qarray[1].add(true);
qarray[2]= new ArrayList();
qarray[2].add("hello");
Try like this:
List<Integer> qarray = new ArrayList<>();
qarray.add(1);
First I believe that you need array and not ArrayList. 2d array can be created as following.
int[][] arr = new int [10][10];
Your next problem is that you tried to assign int constant 1 to variable of other type. The following example shows how to assign int to element of array
arr [0][0] = 1;
According to javadoc, you can not create arrays of ArrayList. Use 2D array instead.
If you need 2D ArrayList anyway, you should have tried this way:
ArrayList<ArrayList<Integer>> listOfLists = new ArrayList<>();
ArrayList<Integer> list1 = new ArrayList<>();
list1.add(1);
list1.add(2);
ArrayList<Integer> list2 = new ArrayList<>();
list2.add(5);
listOfLists.add(list1);
listOfLists.add(list2);
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
you wan to add int,String and boolean then you can use
ArrayList<ArrayList<Object>> listOfLists = new ArrayList<ArrayList<Object>>();
it will help you
ArrayList<Integer>[][] list = new ArrayList[10][10];
list[0][0] = new ArrayList<>();
list[0][0].add(new Integer(10);
try like this.

Java add variable to string array

I have a small code that includes citynames which will be displayed.
Now a want a user can add names with a scanner, I know the code for the scanner but not how to add the variable.
Code I have:
String[] cityNames = { "Tiel", "Culemborg", "Houten", "Geldermalsen", "Meteren", "Buren" };
System.out.println(Arrays.toString(cityNames));
No you cannot do it with a Array since the size is fixed , once it declared.
You are probably looking for Collections. Prefer to Use List interface with ArrayList implementation.
The reason is that the ArrayList is
Resizable-array implementation of the List interface.
List<String> cityNames = new ArrayList<>();
Now you have methods like add, remove, ... and many more useful methods on your cityNames List
You can use a List<String>, get the input value and add it:
List<String> cities = new ArrayList<>();
cities.add(userInput);
List is better to use than array as its length is modifiable.
Arrays have a fixed length. If the amount of Strings in your collection is variable, you´ll have to use a List.
You can add new element to array if index of new element less than the size of array.
arr[i]="some value" // to do this i < arr.length
If array is completely filled with elements when you assign new value to index previous value will override. You can't add more elements than the size of declared since array has fixed size.
Array is fixed size so you can't add the value to it if the size is already filled. For dynamic array use List instead of array.
Do like this
List<String> list = new ArrayList<String>(Arrays.asList("Tiel", "Culemborg", "Houten", "Geldermalsen", "Meteren", "Buren" ));
list.add("new value1");
list.add("new value2");
It's better to use there set, which excludes duplicate entries automatically:
Set<String> cities = new HashSet<String>();
cities.addAll(Arrays.asList("Tiel", "Culemborg", "Houten", "Geldermalsen", "Meteren", "Buren"));
then to add new city just call:
sities.add(newCity);
Scanner input = new Scanner(System.in);
List<String> cityNames = new ArrayList<String>();
//Add the city names to cityNames list...
cityNames.add(input.next());

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;
}

Java ArrayList Index

int[] alist = new int [3];
alist.add("apple");
alist.add("banana");
alist.add("orange");
Say that I want to use the second item in the ArrayList. What is the coding in order to get the following output?
output:
banana
You have ArrayList all wrong,
You can't have an integer array and assign a string value.
You cannot do a add() method in an array
Rather do this:
List<String> alist = new ArrayList<String>();
alist.add("apple");
alist.add("banana");
alist.add("orange");
String value = alist.get(1); //returns the 2nd item from list, in this case "banana"
Indexing is counted from 0 to N-1 where N is size() of list.
Read more about Array and ArrayList
List<String> aList = new ArrayList<String>();
aList.add("apple");
aList.add("banana");
aList.add("orange");
String result = alist.get(1); //this will retrieve banana
Note: Index starts from 0 i.e. Zero
Resource
Using an Array:
String[] fruits = new String[3]; // make a 3 element array
fruits[0]="apple";
fruits[1]="banana";
fruits[2]="orange";
System.out.println(fruits[1]); // output the second element
Using a List
ArrayList<String> fruits = new ArrayList<String>();
fruits.add("apple");
fruits.add("banana");
fruits.add("orange");
System.out.println(fruits.get(1));
Exactly as arrays in all C-like languages. The indexes start from 0. So, apple is 0, banana is 1, orange is 2 etc.
In order to store Strings in an dynamic array (add-method) you can't define it as an array of integers ( int[3] ). You should declare it like this:
ArrayList<String> alist = new ArrayList<String>();
alist.add("apple");
alist.add("banana");
alist.add("orange");
System.out.println( alist.get(1) );
The big difference between primitive arrays & object-based collections (e.g., ArrayList) is that the latter can grow (or shrink) dynamically. Primitive arrays are fixed in size: Once you create them, their size doesn't change (though the contents can).
Here is how I would write it.
String[] fruit = "apple banana orange".split(" ");
System.out.println(fruit[1]);

Categories