I have an arraylist of an arraylist declared like
ArrayList<ArrayList<Integer>> bigList = new ArrayList<ArrayList<Integer>>();
I would then add to this bigList by bigList.add(arraylist).
I then have a class that takes ArrayList<Integer> as a construcor parameter. My question is how do I send a certain ArrayList in bigList to this class as a constructor parameter? I can iterate through my bigList with
for(ArrayList<Integer> list : bigList) {
for(Integer num : list)
System.out.println(num);
}
but I have not been able to send a whole ArrayList element to another class. Thanks a bunch.
You can select an ArrayList at a particular index and pass it to a constructor as follows:
int index = 2; // the index of the list you want to pass to the constructor
MyNewObject newObject = new MyNewObject(bigList.get(index));
Have you tried:
List<SomeClass> sList = new ArrayList<>();
for(ArrayList<Integer> list : bigList) {
sList.add(new SomeClass(list));
}
This would work fine if you are looking to iterate though all lists in bigList and construct new instances from all of them. Alternatively, if you just want to create one such object for a specific list at index "i" of bigList:
SomeClass s = new SomeClass(bigList.get(i));
Related
I have to use 10 ArrayLists for a project, instead of creating 10 separate arraylists. I was told to use: ArrayList<ArrayList<Integer>> lists = new ArrayList<>(); and to create the 10 arrays to use: for(int i=0;i<10;i++){ lists.add(new ArrayList<Integer> ());
I have never studied arraylists inside of a arraylist, so this is very new to me. How do I access the arrays inside of the array? They do not have a name that I can see to access, so how do I call each individual arraylist?
You can create an arraylist of arraylists as shown in the code below. If you want to access all the inner array lists just use a for each loop. If you want a specific list (array list is ordered) just use the index (both ways are shown in the example below):
ArrayList<ArrayList<String>> listOfLists = new ArrayList<ArrayList<String>>();
ArrayList<String> firstList = new ArrayList<String>() {{
add("A");
add("B");
add("C");
}};
ArrayList<String> secondList = new ArrayList<String>() {{
add("D");
add("E");
add("F");
}};
listOfLists.add(firstList);
listOfLists.add(secondList);
//access all inner lists
for(ArrayList<String> innerList:listOfLists) {
System.out.println("INNER LIST --> "+innerList);
}
//access specific list
System.out.println(listOfLists.get(1));
To add a number to a list in the list of lists, you have to get it using its index, then you can add to it.
lists.get(0).add(42);
Let say you wanna access some index of a particular ArrayList inside the ArrayList of ArrayList
e.g.
arrayListOfarrayList.get(indexOfArrayList).get(indexOfElement);
If you wanna add something
arrayListOfarrayList.get(indexOfArrayList).add(yourElement);
You can refer to ArrayList API docs for more details
https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
I want to know the shortcut for doing this :
class{ ArrayList a1=new ArrayList();
ArrayList a2=new ArrayList();
ArrayList a3=new ArrayList();
.....& so on
}
So instead of writing each reference, how can I write an array of references 'with ArrayList' ?
you can use `List<ArrayList> list = new ArrayList<ArrayList>();`. In this you can add any number of `ArrayList` Objects to `list` reference.
Find the below :
List<ArrayList> list = new ArrayList<ArrayList>();
list.add(new ArrayList());
list.add(new ArrayList());
list.add(new ArrayList());
list.add(new ArrayList());
// ....
list hold ArrayList references in inserted order. You can access the ArrayList using index which zero based.
// to access the ArrayList reference.
ArrayList a1 = list.get(0);
Use an array of ArrayList. And loop.
ArrayList a1, a2, ... , a100;
ArrayList[] arrayLists = new ArrayList[100];
for (ArrayList arrayList : arrayLists) {
arrayList = new ArrayList();
}
But creating different references array is not a good design.
For example you can create array list array like below:
ArrayList[] a = new ArrayList[4];
Before implementing this you clear with your requirement , why you need to create these many references.
And also while creating ArrayList it's better to use reference creation like below:
List<String> a = new ArrayList<String>();
Always use generics while working on JAVA collections.
For your requirement to store word and it's permutations, I would suggest below process:
Step1: Create WordPermutations class
public Class WordPermutations{
public string word;
public ArrayList<String> permutations = new ArrayList<String>();
public void setWord(String word){
this.word = word;
}
public void setPermutations(ArrayList<string> permutations){
this.permutations = permutations;
}
public String getWord(){
return this.word;
}
public ArrayList<String> getPermuatations(){
return this.permuations;
}
}
Step2: Use this class to create your arrayList objects like below:
Class MainPermutation{
public static void main(String args[]){
// your code to get all your words and their permutations
// Now add them like below
ArrayList<WordPermutations> words = new ArrayList<WordPermutations>();
//your loop to iterate words and their permutations
for (int i=0;i<words.length;i++){
WordPermutations wordP = new WordPermutations();
wordP.setWord(word); //String word
wordP.setPermutations(permutations); //arraylist of permutations
words.add(wordP); //adding your word and it's permutations to class
}
}
}
Step3: Now read your arrayList array accordingly
with above process you can store n number of words.
Hope it helps you.
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
i want to store Arraylist inside Another List, some thing like this i know its wrong but pretty much like this....
List list=new ArrayList();
list.add(new("element1","element2","element3",element4=?);
list.add(new("element5","element6","element7",element8=?);
now if u see the above code its ok and fine to add elements or first row to list up to third element but the fourth element is another array[string array] how to add it or append it to the first row of element.
same with the second row.
NOTE:- element4 and element8 are also differ in length means element4 has 2 string and element 8 has 10 strings.
when i display the list it should show list like this
The first row of list is
element1 element2 element3 element4.1 element4.2
the second row of list is
element5 element6 element7 element8.1 element8.2 element8.3 element8.4 element8.5 element8.6 element8.7 element8.9 element8.10
So from what I understood about your question, you need a List<List<String>>. Do it as follows:
List<String> strs1 = new ArrayList<String>();
strs1.add("element1");
strs1.add("element2");
List<String> strs2 = new ArrayList<String>();
strs2.add("element3");
And then
List<List<String>> listOfList = new ArrayList<List<String>>();
listOfList.add(strs1);
listOfList.add(strs2);
OR
List<List<String>> asList = Arrays.asList(strs1, strs2);
Have you tried following way:
List list = new ArrayList();
list.add(Arrays.asList("element1", "element2", "element3",
Arrays.asList("element4.1", "element4.2")));
list.add(Arrays.asList("element5", "element6", "element7",
Arrays.asList("element8.1", "element8.2", "element8.3")));
// print values
System.out.println(list.get(0));
System.out.println(list.get(1));
Unify it to a List of lists of lists, a three dimensional matrix - even if your first elements are single values, it makes sense to wrap them in lists just to simplify the code:
List<List<List<String>>> matrix = new ArrayList<List<List<String>>>();
List<List<String>> row = new ArrayList<List<String>>();
matrix.add(row);
List<String> column1 = new ArrayList<String>();
column1.add("element1");
row.add(column1);
List<String> column2 = new ArrayList<String>();
column1.add("element2.1");
column1.add("element2.2");
row.add(column2);
You can add lists to other lists by doing something like so: List<List<String>> myList = new ArrayList<List<String>>();.... However, seeing that you are adding items which have a different type, I would recommend you do the following (assuming you always have 3 array lists and 1 array):
Create a new class which takes in 4 arguments, these being the 3 array lists and the 1 array.
Have your class override its own toString() method in such a way that it will iterate over the elements and print their content in whatever way you would like.
Create an list using generics, using something like this: List<MyClass> myList = new ArrayList<MyClass>();.... In this case, MyClass is the class I have described in point 1. This will allow you to create a type safe structure which does not need to do any casting, thus making your code look cleaner and probably run slightly faster.
Seeing that you say that the elements can contain list of strings of various lengths, you can do something like this:
public class MyClass
{
private List<String> arrayList1;...
private String[] myArray;...
public MyClass(List<String> list1, ..., String[] myArray)
{
this.arrayList1 = list1;
this.myArray = myArray;
...
}
...
#Override
public String toString()
{
StringBuilder sb = new StringBuilder();
//iterate adding your list contents to your string builder.
return sb.toString();
}
}
Adding your elements then will be something like this:
...
List<String> arrayList1 = ...;
arrayList1.add("...");...
String[] myArray = ...;
MyClass myClass = new MyClass(arrayList1, ..., myArray);
System.out.println(myClass.toString());
Can somebody please explain me why I can't cast List<> to ArrayList<> with first approach and I do with second one? Thank you.
First approach:
ArrayList<Task> tmp = ((ArrayList<Task>)mTrackytAdapter.getAllTasks(token));
Second approach:
ArrayList<Task> tmp = new ArrayList<Task>(mTrackytAdapter.getAllTasks(token));
When you do the second one, you're making a new arraylist, you're not trying to pretend the other list is an arraylist.
I mean, what if the original list is implemented as a linkedlist, or some custom list? You won't know. The second approach is preferred if you really need to make an arraylist from the result. But you can just leave it as a list, that's one of the best advantages of using Interfaces!
When you are using second approach you are initializing arraylist with its predefined values.
Like generally we do
**ArrayList listofStrings = new ArrayList<>();
**
Let's say you have an array with values, now you want to convert this array into arraylist.
you need to first get the list from the array using Arrays utils.
Because the ArrayList is concrete type that implement List interface. It is not guaranteed that method asList, will return this type of implementation.
List<String> listofOptions = (List<String>) Arrays.asList(options);
then you can user constructoru of an arraylist to instantiate with predefined values.
ArrayList<String> arrlistofOptions = new ArrayList<String>(list);
So your second approach is working that you have passed values which will intantiate arraylist with the list elements.
More over
ArrayList that is returned from Arrays.asList is not an actual arraylist, it is just a wrapper which doesnt allows any modification in the list.
If you try to add or remove over Arrays.asList it will give you
UnsupportedOperationException
Try running the following code:
List<String> listOfString = Arrays.asList("Hello", "World");
ArrayList<String> arrayListOfString = new ArrayList(listOfString);
System.out.println(listOfString.getClass());
System.out.println(arrayListOfString.getClass());
You'll get the following result:
class java.util.Arrays$ArrayList
class java.util.ArrayList
So, that means they're 2 different classes that aren't extending each other. java.util.Arrays$ArrayList signifies the private class named ArrayList (inner class of Arrays class) and java.util.ArrayList signifies the public class named ArrayList. Thus, casting from java.util.Arrays$ArrayList to java.util.ArrayList and vice versa are irrelevant/not available.
The second approach is clearly wrong if you want to cast. It instantiate a new ArrayList.
However the first approach should work just fine, if and only if getAllTasks return an ArrayList.
It is really needed for you to have an ArrayList ? isn't the List interface enough ? What you are doing can leads to Runtime Exception if the type isn't correct.
If getAllTasks() return an ArrayList you should change the return type in the class definition and then you won't need a cast and if it's returning something else, you can't cast to ArrayList.
Just try this :
ArrayList<SomeClass> arrayList;
public SomeConstructor(List<SomeClass> listData) {
arrayList.addAll(listData);
}
You can cast List<> to ArrayList<> if you understand what you doing. Java compiler won't block it.
But:
It's bad practice to casting parent type to child type (or interface to implementation type) without checking.
This way better:
if (list instanceof ArrayList<Task>) {
ArrayList<Task> arraylist = (ArrayList<Task>) list;
}
Maybe you don't need implementation type as reference. Look SonarQube warning https://sbforge.org/sonar/rules/show/squid:S1319. You can avoid this casting in the most cases.
You can use Guava method:
ArrayList<Task> arraylist = Lists.newArrayList(list);
The first approach is trying to cast the list but this would work only if the List<> were an ArrayList<>. That is not the case. So you need the second approach, that is building a new ArrayList<> with the elements of the List<>
Because in the first one , you're trying to convert a collection to an ArrayList.
In the 2nd one , you just use the built in constructor of ArrayList
May be:
ArrayList<ServiceModel> services = new ArrayList<>(parking.getServices());
intent.putExtra("servicios",services);
import java.util.List;
import java.util.Arrays;
import java.util.*;
public class Merge
{
public static void main(String[] args) {
// This is normal way
// List<Integer> l1 = new ArrayList<Integer>(); l1.add(2); l1.add(5); l1.add(10); l1.add(22);
// List<Integer> l2 = new ArrayList<Integer>(); l2.add(3); l2.add(8); l2.add(15);
//Array.asList only have the list interface, but ArrayList is inherited from List Interface with few more property like ArrayList.remove()
List<Integer> templ1 = Arrays.asList(2,5,10,22);
List<Integer> templ2 = Arrays.asList(3,8,12);
//So creation of ArrayList with the given list is required, then only ArrayList.remove function works.
List<Integer> l1 = new ArrayList<Integer>(templ1);
List<Integer> l2 = new ArrayList<Integer>(templ2);
List<Integer> l3 = new ArrayList<Integer>();
Iterator itr1 = l1.iterator();
while(itr1.hasNext()){
int x = (Integer) itr1.next();
Iterator itr2 = l2.iterator();
while(itr2.hasNext()) {
int y = (Integer) itr2.next();
if(x < y) {
l3.add(x);
break;
}
else{
l3.add(y);
itr2.remove();
}
}
}
Iterator it = l1.iterator();
while (it.hasNext()){
int k = (Integer) it.next();
if (l3.contains(k)){
continue;
}
else{
l3.add(k);
System.out.println(k);
}
}
Iterator itr2 = l2.iterator();
while (itr2.hasNext()){
int k = (Integer) itr2.next();
l3.add(k);
}
System.out.println(l3);
}
}