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);
}
Related
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];
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.
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);
I have an array and i want to compare the first element of this array with every element of another array in an Arraylist?
The purpose of doing this is to check whether or not the first element of the array exist in the another array of an Arraylist.
is this possible?
if yes, how?
List<List<String>> arrayst = new ArrayList<List<String>>();
List<List<String>> arrayqu = new ArrayList<List<String>>();
List<List<String>> arrayya = new ArrayList<List<String>>();
List<String> items = Arrays.asList(line.split(":",-1));
// i want to compare 1st element of items with 3 of the list above.
Create a different class and try something like this -
public class StackOverflow {
public void compare(List<String> items, List<List<String>> list){
String itemToBeCompared=items.get(0);
for(List<String> l:list){
if(l.contains(itemToBeCompared)){
System.out.println("Its Present");
}
else{
System.out.println("Not Present");
}
}
}
}
Then in the main method do something like this -
List<List<String>> arrayst = new ArrayList<List<String>>();
List<List<String>> arrayqu = new ArrayList<List<String>>();
List<List<String>> arrayya = new ArrayList<List<String>>();
List<String> items = Arrays.asList(line.split(":",-1));
StackOverflow st=new StackOverflow();
st.compare(items,arrayst);
st.compare(items,arrayqu);
st.compare(items,arrayya);
Hope this helps! Please let me know if this works for you.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Assigning an array to an ArrayList in Java
I need to convert a String[] to an ArrayList<String> and I don't know how
File dir = new File(Environment.getExternalStorageDirectory() + "/dir/");
String[] filesOrig = dir.list();
Basically I would like to transform filesOrig into an ArrayList.
You can do the following:
String [] strings = new String [] {"1", "2" };
List<String> stringList = new ArrayList<String>(Arrays.asList(strings)); //new ArrayList is only needed if you absolutely need an ArrayList
Like this :
String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
List<String> wordList = new ArrayList<String>(Arrays.asList(words));
or
List myList = new ArrayList();
String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
Collections.addAll(myList, words);
List<String> list = Arrays.asList(array);
The list returned will be backed by the array, it acts like a bridge, so it will be fixed-size.
List myList = new ArrayList();
Collections.addAll(myList, filesOrig);
You can loop all of the array and add into ArrayList:
ArrayList<String> files = new ArrayList<String>(filesOrig.length);
for(String file: filesOrig) {
files.add(file);
}
Or use Arrays.asList(T... a) to do as the comment posted.
You can do something like
MyClass[] arr = myList.toArray(new MyClass[myList.size()]);