adding elements to the ArrayList nested inside another Arraylist - java

I have nested ArrayList that looks like that in Java:
myArrayList = [element1, element2, [element3]]
I would like to add elements so the ArrayList will look like that:
myArraylist = [element1, element2, [element3, element4, element5]]
I tried to use;
myArrayList.get(2).add(elemet4);
myArrayList.get(2).add(elemet5);
but as a result I got:
myArraylist = [element1, element2, [element3], element4, element5]
Any hints how to resolve that will be much appreciated.
edit:
My bad, I should have attached Java code and avoid misleading you guys. Anyway here it is:
ArrayList<ArrayList<String>> finalArray = new ArrayList<ArrayList<String>>();
ArrayList<String> finalArrayTempCopy = new ArrayList<String>();
ArrayList<Integer> transactionTemp = new ArrayList<Integer>();
private ArrayList<Integer> addTransaction(){
System.out.println("Enter transaction amount:");
int amount = scanner.nextInt();
scanner.nextLine();
transactionTemp.add(Integer.valueOf(amount));
return transactionTemp;
}
private int searchName(String name){
int indexImienia = customerName.indexOf(name);
return indexImienia;
}
public void sumUp(){
String name = "Tom";
String branch = "First";
int indexImienia = searchName(name);
String transactionsAsString = transactionTemp.toString();
finalArrayTemp.add(name);
finalArrayTemp.add(branch);
finalArrayTemp.add(transactionsAsString);
finalArrayTempCopy = new ArrayList<String>(finalArrayTemp);
finalArray.add(indexImienia, finalArrayTempCopy);
}
Later in the code if I want to add single transaction I use the following method
public void addSingleTransaction(){
int indexImienia = 0;
int amount =20;
finalArray.get(indexImienia).add(2, String.valueOf(amount));
}
Editing my post I realised that the problem might lie with converting ArrayList into string and adding it to finalArray as string. Anyway, I will be grateful for your insight.

i think you looking for
List<Object> list1=new ArrayList<Object>();
List<Object> list=new ArrayList<Object>();
list.add("element1");
list.add("element2");
list1.add("element3");
list.add(list1);
List<Object> listobj=(List<Object>) list.get(2);
listobj.add("element4");
listobj.add("element5");
System.out.println(list);
you are adding element to your parent list not your nested list, for which you have to store the reference of your nested list, then you can add other elements.

Seems like you are looking for:
ArrayList<Object> myArrayList = new ArrayList<Object>();
ArrayList<Integer> list1 = new ArrayList<Integer>;
myArrayList.add(element1);
myArrayList.add(list1);
Or
ArrayList<ArrayList<Integer>> myArrayList = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> list1 = new ArrayList<Integer>;
ArrayList<Integer> list2 = new ArrayList<Integer>;
list1.add(element1);
list2.add(element2);
list2.add(element3);
myArrayList.add(list1);
myArrayList.add(list2);
Assuming, element is an Integer

As per the psuedo code shared, There is some issue with your main array declaration.
ArrayList can only have one type of data in it. Therefore, your declaration of array can be like :
ArrayList<Element> arr = new ArrayList<Element>();
or to store List in it:
ArrayList<ArrayList<Element>> ar2 = new ArrayList<ArrayList<Element>>();
If you wish to store both type of values in same structure
you can use Object for storing any type of value, since it is the root of all classes.
In this case your declaration will be something like:
ArrayList<Object> arrOuter = new ArrayList<Object>();
Element e1 = new Element();
Element e2 = new Element();
arrOuter.add(e1);
arrOuter.add(e2);
ArrayList<Element> arrNested = new ArrayList<Element>();
Element e3 = new Element();
arrNested.add(e3);
arrOuter.add(arrNested);
But in this case you can not directly call add method on data returned by arrOuter, since the data returned is of Object class. You have to explicitly cast it to list and then add another data.
Element e4 = new Element();
Element e5 = new Element();
((ArrayList) arrOuter.get(2)).add(e4);
((ArrayList) arrOuter.get(2)).add(e5);

Related

Why there is no error when I put String to a ArrayList<Integer> array in Java

public class Main {
public static void main(String[] args) {
List[] list = new ArrayList[3];
list[0] = new ArrayList<Integer>();
list[0].add("string");
ArrayList<Integer> arr = new ArrayList<>();
arr.add("string");
}
}
Frist question: I already state that the ArrayList should accept Interger. But it do not throw error when I try to assign a "string" into this ArrayList. I really don't know why this happen.
Seconde question: Why I can declare a list by this "List[] list = new ArrayList[3];"
The reason is that
List[] list = new ArrayList[3];
By doing it,you make list accept any parameters,in this case list[0] = new ArrayList<Integer>(); works similar to list[0] = new ArrayList<>();
If you want to it just accept Integer,you need to do it as following
List<Integer>[] list = new ArrayList[3];

Java 2D arraylists

I cant understand 2D arraylists, they are confusing me, I can understand 2D arrays however as I worked with them before in C and in Python as "nested lists"
can someone explain the difference between these 2 codes?
ArrayList<ArrayList<String>> biDemArrList = new ArrayList<ArrayList<String>>();
ArrayList<String> temp = new ArrayList<String>(); // added ()
temp.add("Hello world.");
temp.add("sup");
biDemArrList.add(temp);
ArrayList<String> it = new ArrayList<String>();
it.add("1");
it.add("0");
biDemArrList.add(it);
System.out.println(temp);
System.out.println(it);
System.out.println(biDemArrList);
and this one :
ArrayList[][] table = new ArrayList[10][10];
table[0][5] = new ArrayList();
table[1][1] = new ArrayList();
for (int i = 0; i < 12; i++) {
table[0][5].add("0");
}
for (int i = 0; i < 9; i++) {
table[1][1].add("1");
}
System.out.println(table[0][5]);
System.out.println(table[9][9]);
Like in C arrays of non primitive types are not initialized (only arrays of primitive types are...).
ArrayList[][] table = new ArrayList[10][10];
table[0][5] = new ArrayList();
table[1][1] = new ArrayList();
Here you create an array of 100 elements but you only initialize 2 Elements.
ArrayList is resizable-array implementation of the List interface. This class. Most of the developers choose Arraylist over Array as it’s a very good alternative of traditional java arrays.
You can add any object to List, e.g. null, String, Object, String[]. ArrayList<String> also is object, it's means you can add to list.
You said I have ArrayList which can add other ArrayList. The result will be ArrayList<ArrayList>>.
But we want to add only String's to inner ArrayList. And we create ArrayList<String>
So, We have list of string ArrayList<String> which can be added to other list ArrayList<ArrayList>>
ArrayList<ArrayList<String>> mainArrayList = new ArrayList<ArrayList<String>>();
ArrayList<String> subArrayList = new ArrayList<String>();
/* Added elements into subArrayList */
subArrayList.add("Yogesh");
subArrayList.add("Pawar");
ArrayList<String> subArrayList2 = new ArrayList<String>();
/* Added elements into subArrayList2 */
subArrayList2.add("Java");
subArrayList2.add("Programmer");
/* Adding elements into mainArrayList */
mainArrayList.add(subArrayList);
mainArrayList.add(subArrayList2);
for (int i = 0; i < mainArrayList.size(); i++) {
for (int k = 0; k < mainArrayList.get(i).size(); k++) {
System.out.print(" " + mainArrayList.get(i).get(k));
}
System.out.println();
}
The difference between
List of List
ArrayList<ArrayList<String>> biDemArrList = new ArrayList<ArrayList<String>>();
and
Array of Array of List
ArrayList[][] table = new ArrayList[10][10];
Is that the second one is not actually two-dimensional, it is three-dimensional. You end up with 10 Arrays of length 10 that you can put ArrayLists into. Where as in the List of List example you have a List you can put other Lists into.
Using the Object[][] or primitive[][] you have to allocate the 2D array with exact number of "rows" and "columns" like new Object[2][8].
On the other hand with ArrayList<ArrayList<...>> try to understand the following code:
ArrayList<ArrayList<String>> biDemArrList = new ArrayList<>();
ArrayList<String> a0 = new ArrayList<>();
a0.add("string_1");
ArrayList<String> a1 = new ArrayList<>();
a1.add("strfdfas");
a1.add("adfadsfasdfasdfasfaf");
biDemArrList.add(a0);
biDemArrList.add(a1);
biDemArrList.stream().forEach(System.out::println);
The first "row" has one element, and the second one has two elements. This is only an example... With arr[][] you cannot achieve this.
What is reason behind this not sure, But i would share my experience here,
Array is the fixed size of data structure, once we initialize the array we can't modify the size. To resolve this we have ArrayList comes to picture. Arraylist has variable lenght.
In your second code snippet, if you are looking for fixed sized of 2D ArrayList, I would suggest to go 2D Arrays.
If you want to get benefit of Collection features, later you can convert Arrays to ArrayList object.

Add an arraylist to 2d arraylist in java [duplicate]

This question already has answers here:
Add ArrayList to another ArrayList in java
(6 answers)
Closed 6 years ago.
I have a 2D arraylist which I want to fill it with several 1D arraylists. My code is the following:
ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
while (ts2.next()) {
list.add( ts2.getString("userName");
list.add(ts2.getString("userId"));
array.add(list);
list.clear();
}
I have noticed that list.clear() deletes the elements from the list however also deletes the element from the array. In the end, both array and list are empty. How can I add list in array and clear the list after array.add(list)
You can clone the list:
array.add(list.clone());
Or you can instantiate the list object within the loop itself:
ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
while (ts2.next()) {
ArrayList<String> list = new ArrayList<String>();
list.add( ts2.getString("userName");
list.add(ts2.getString("userId"));
array.add(list);
}
Then you wouldn't even need to clear it.
You can do this:
ArrayList<String[]> arr = new ArrayList<String[]>();
String[] str = new String[2];
while (ts2.next()) {
str[0] = ts2.getString("userName");
str[1] = ts2.getString("userId");
arr.add(str);
}
if you would an arraylist also:
ArrayList<ArrayList<String>> arr = new ArrayList<ArrayList<String>>();
while (ts2.next()) {
ArrayList<String> arrString = new ArrayList<String>();
arrString.add(ts2.getString("userName"));
arrString.add(ts2.getString("userId"));
arr.add(arrString);
}
You can create a new instance of ArrayList<> to be added in the existing one.
while (ts2.next()) {
List<String> list = new ArrayList<>();
list.add(ts2.getString("userName"));
list.add(ts2.getString("userId"));
array.add(list);
}
However the better approach is to map these values into a new instance of a class.
List<MyClass> = new ArrayList<>();
while (ts2.next()) {
MyClass i = new MyClass(ts2.getString("userName"), ts2.getString("userId"));
array.add(i);
}

Initializing multiple Lists in java simultaneously

I'm trying to initialize a List in Java but I want to know if there's a more elegant way of initializing multiple lists with the same types.
So far I've done the following:
List<Model> list1 = new List<>();
List<Model> list2 = new List<>();
List<Model> list3 = new List<>();
But I'm trying to initialize about 10 different lists of the same type and it seems very ugly.
I've also tried doing:
List<Model> list1, list2, list3 = new List<>();
But this doesn't work.
After searching for the answer, all I could find were tips on how to initialize an array with multiple variables in one line using the asList() method but that's not what I'm trying to do.
Is this even possible?
You can use a Map where the key represents the list name and the value represents a List
Map<String,List<Model>> lists = new HashMap<>();
You can then populate the list in a for loop :
for(int i=0;i<10;++i) {
lists.put("list"+(i+1),new ArrayList<Model>());
}
You can access the lists using :
lists.get("list1").add(new Model(...));
lists.get("list2").add(new Model(...));
Disclaimer : I have not tried compiling this code since I am not on a computer.
If you have 10 lists or whatever, it's time to think: probably you need an array or list of lists.
List<List<Model>> lists = new ArrayList<>();
for(int i=0; i<10; i++) lists.add(new ArrayList<>());
// later in code instead of list5.add(...)
lists.get(5).add(...)
List is an interface (abstract type) and cannot be instantiated. You will have to use ArrayList as shown below. You can try:
List<Model> list1 = new ArrayList<Model>(), list2 = new ArrayList<Model>();
This should work as well
List<Model> list1 = new ArrayList<Model>(), list2 = new ArrayList<Model>(), list3 = new ArrayList<Model>();
The closest possible thing that you can do is following
List<Model> a = new ArrayList<>(), b = new ArrayList<>(), c = new ArrayList<>(), d = new ArrayList<>();
But either of the approach you consider has same memory consumption impact.
Here's my answer:
#SuppressWarnings({"unchecked"})
List<Model>[] lists = new List[3];
for(List list : lists) {
list = new ArrayList<Model>();
}
List<Model> list1 = lists[0];
List<Model> list2 = lists[1];
List<Model> list3 = lists[2];

Manually accessing an ArrayLists with a ArrayList

I'm working with Depth First Search program and I'm trying to create a Adjacency List Representation.
I read through some articles stating that an creating ArrayLists within an ArrayList would be the best representation.
Let's say I initialized the arraylist within a arraylist like so:
List<List<Integer>> adjList = new ArrayList<List<Integer>>();
My question is how would you input data into the arraylist MANUALLY. I'm trying to understand the concept of arraylist with an arraylist before I begin my programming. If someone could possibly insert data into this arraylist so I could see the proper way of setting up.
Any additional input on anything I might need or take in consideration is recommended.
BTW: This is not a homework assignment just using personal time looking through my old textbooks.
Let's say you want to add 2 lists, one with 1 and 2 and the other with 10 and 20. A very manual way of adding could be:
List<List<Integer>> adjList = new ArrayList<List<Integer>>();
adjList.add(new ArrayList<Integer>()); // initialise new ArrayList<Integer>
adjList.get(0).add(1); // add value one by one
adjList.get(0).add(2);
adjList.add(new ArrayList<Integer>());
adjList.get(1).add(10);
adjList.get(1).add(20);
You could also write it this way:
List<List<Integer>> adjList = new ArrayList<List<Integer>>();
ArrayList<Integer> a1 = new ArrayList<Integer>(); // initialise new ArrayList<Integer>
a1.add(1); // add value one by one
a1.add(2);
adjList.add(a1);
ArrayList<Integer> a2 = new ArrayList<Integer>(); // initialise new ArrayList<Integer>
a2.add(10); // add value one by one
a2.add(20);
adjList.add(a2);
Well, a list of a list of Integer objects could be done as such:
List<List<Integer>> adjList = new ArrayList<List<Integer>>();
List<Integer> li = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
li.add(i);
}
adjList.add(li);
Add to each sublist, and then add the sublist.
The adjList can contain the elements of the type List<Integer>, so create one and add using add(E element) function as we would for adding an element:
ArrayList<Integer>aList = new ArrayList<>();
adjList.add(aList);
Then to add an element to the element(which has the type List<Integer>) of adjList: you can try getting it using get(index) and add your element:
adjList.get(0).add(10);
adjList.get(0).add(22);
Try adding a second list and get it's index using get(1) and add the Integer element to the list at index 1 as the above example suggest. There are other known function too. Please check the class ArrayList<E> documentation page.
This will help
public static void main(String[] args){
//creating a new ArrayList of List of Integers
ArrayList<List<Integer>> integerListContainer = new ArrayList<List<Integer>>();
//Creating the first child arraylist of Integers
ArrayList<Integer> firstChildintegerList = new ArrayList<Integer>();
//filling the values 1,2,3 in it
firstChildintegerList.add(1);
firstChildintegerList.add(2);
firstChildintegerList.add(3);
//adding this integer list to the parent list
integerListContainer.add(firstChildintegerList);
//Creating the second child arraylist of Integers
ArrayList<Integer> secondChildintegerList = new ArrayList<Integer>();
//filling the values 10,20,30 in it
secondChildintegerList.add(10);
secondChildintegerList.add(20);
secondChildintegerList.add(30);
//adding this integer list to the parent list
integerListContainer.add(secondChildintegerList);
System.out.println("Printing the parent list to see what it has: ");
System.out.println(integerListContainer.toString());
}
Hope it clearly explains what happens

Categories

Resources