add ArrayList to multiple ArrayList in java - java

Hi i have problem with ArrayLists i have 3 lists
ArrayList1<Integer>=[1,2,3]
ArrayList2<Integer>=[]
ArrayList3<ArrayList<Integer>>=[]
ArrayList1 elements are used for adding values to ArrayList2
for example
for(int i:ArrayList1)
{
for(int a=0;a<i;a++)
{
ArrayList2.add(a);
}
}
and that works fine no problem there but now i want to for every element in ArrayList1 to add ArrayList2 to ArrayList3 this is what I have come up with but it does not work
for(int i:ArrayList1)
{
for(int a=0;a<i;a++)
{
ArrayList2.add(a);
}
ArrayList3.add(ArrayList2);
}

Simply use addAll, and Collections.fill.
Example
list2.addAll(list1);
list3 = new ArrayList<ArrayList<Integer>>(list1.size());
Collections.fill(list3, list2);
Note that list3 will be filled with the same instance of list2.
This means that every change to list2 will be reflected in each element of list3.
If this is not the behavior you're expecting, iterate over the length of list1 and add a new ArrayList<Integer>(list2).

for(int a=0;a<i;a++)
is wrong. You must not stop at a < i, it makes no sense! You want to add the whole arrayList2 to ArrayList3, not a number of integers equal to the value of the int i in ArrayList1.

Related

Java - how to find a letter in a string in ArrayList the duplicate string

I have a problem with some tasks. I have to find words that contains letter "r" and duplicate these words. I tried to do this with for loop:
for(int i = 0; i < list.size(); i++){
if(list.get(i).contains("r")){
list.add(list.get(i));
}
But it doesnt work at all. When i add new element to array would it make it bigger? Then list.size will change and loop wont manage to get to the last element of array? Also duplicated word should be just after the original one, for example input:
show
ram
cat
output:
show
ram
ram
cat
Really i have no idea how to duplicate it.
This also doesnt work:
for(int i = 0; i < list.size(); i++){
if(list.get(i).contains("r")){
list.add(i+1, list.get(i));
}
After adding duplicate for element which contains letter r, you would eventually move to that duplicate and since it also contains r you will add duplicate for it, and then after visiting that another copy you will add another duplicate for it, and so on... infinitely so your loop will not end (until you will run of memory).
To avoid it, after duplicating element you need to jump to next element after that duplicate. You can do it by additional incrementing i after
list.add(i+1, list.get(i));
i++;
or
list.add(++i, list.get(i));
You could create a copy of your original List and add elements to it. That way the list you're iterating over doesn't change size.
For example:
List<String> list = Arrays.asList("show", "ram", "cat");
List<String> result = new ArrayList<>(list);
list.stream().filter(a -> a.contains("r")).forEach(a -> result.add(a));
Depending on the type of your list, this can easily be achieved with a ListIterator, which has an add method that adds an element exactly after the current element, but does not iterate it.
List<String> list = new ArrayList<>( Arrays.asList( "show", "ram", "cat" ) );
ListIterator<String> iterator = list.listIterator();
while ( iterator.hasNext() ) {
String value = iterator.next();
if ( value.contains("r") ) {
iterator.add(value);
}
}
System.out.println( list );
The output from this is:
[show, ram, ram, cat]
This will work with ArrayList and LinkedList, but not with the particular List that comes directly from Arrays.asList, because it is unmodifiable.
Keep it simple and just use another List<String>.
public static void main(String[] args) {
List<String> input = Arrays.asList("show", "ram", "cat");
List<String> result = new ArrayList<>();
for (String s : input) {
if (s != null && s.contains("r")) {
result.add(s);
}
result.add(s);
}
System.out.println(result);
}
Will print that you want. Hope it helps!
You need find word which contains letter r and after that add all found words to the list:
List<String> list = Arrays.asList("black", "red", "blue");
List<String> result = list.stream()
.filter(i->i.contains("r"))
.collect(Collectors.toList());
list.addAll(result);

Type mismatch when creating List of objects

I am trying to part the mainListarraylist to 3 sublist Arraylist and then add it as sublist in other arraylist mainSublist but I am getting this error:
How can I fix it?
I appreciate any help.
1)-Type mismatch: cannot convert from List to ArrayList
2) -The method add(RootCreator) in the type ArrayList is not applicable for the arguments (ArrayList)
Code:
ArrayList<RootCreator> mainList = new ArrayList<RootCreator>();
for (String key : names) {
RootCreator rootcreat = join_line(path, key);
mainList.add(rootcreat);
}
ArrayList<RootCreator> mainSublist = new ArrayList<RootCreator>();
for(int i= 0 ; i < mainList.size(); i++){
int index = i*3;
//the error 1 is here
ArrayList<RootCreator> sublist = mainList.subList(0, index);
//error 2 is here
mainSublist.add(sublist);
}
All List are not ArrayList, so when you use sublist you get a generic List. On the other hand, the method to add a collection to another collection is addAll instead add.
List<RootCreator> mainList = new ArrayList<RootCreator>();
for (String key : names) {
RootCreator rootcreat = join_line(path, key);
mainList.add(rootcreat);
}
List<RootCreator> mainSublist = new ArrayList<RootCreator>();
for(int i= 0 ; i < mainList.size(); i++){
int index = i*3;
//the error 1 is here
List<RootCreator> sublist = mainList.subList(0, index);
//error 2 is here
mainSublist.addAll(sublist);
}
The subList method returns a List, not an ArrayList, and you cannot assign a List to an ArrayList. In fact, the List returned by the subList method is not an ArrayList.
If it needs to be an ArrayList, then create an ArrayList out of the sub list.
ArrayList<RootCreator> sublist = new ArrayList<>(mainList.subList(0, index));
If you just need a List, then make sublist a List instead.
List<RootCreator> sublist = mainList.subList(0, index);
You can't add an ArrayList<RootCreator> to an ArrayList<RootCreator>; you must add a RootCreator. If you want to add the elements of sublist to another list, then use the addAll method.
mainSublist.addAll(sublist);
OK, let's look at the two errors here:
//the error 1 is here
ArrayList<RootCreator> sublist = mainList.subList(0, index);
This is telling you that you're trying to assign something of the type List to a variable that's declared as an ArrayList. While an ArrayList is a subtype of List, it doesn't work both ways - you can assign an ArrayList to a List, but not vice versa. So let's change your declaration:
//the error 1 was here, but fixed.
List<RootCreator> sublist = mainList.subList(0, index);
The second one is slightly different:
//error 2 is here
mainSublist.add(sublist);
Here, you've got a list defined to hold items of the type RootCreator - but you're not adding RootCreator items, you're adding a list of them. So if you want to have the list hold other lists, you need to specify that when you create it:
ArrayList<List<RootCreator>> mainSublist = new ArrayList<List<RootCreator>>();
But, if you're trying to just keep a single list and want to add everything from the sublists, then instead, change your code to:
//error 2 was here, but Fixed
mainSublist.addAll(sublist);

How a list consists of lists could be passed by value (not reference) in java method?

I see how to pass an ArrayList by its value so that the called method doesn't modify the original Arraylist. Passing ArrayList as value only and not reference However, I'm trying to pass an ArrayList that itself contains other Arraylists; that is Arraylist of Arraylist.
public class Test {
public static void main(String[] args){
ArrayList<ArrayList<Integer>> lists = new ArrayList<ArrayList<Integer>>();
for(int j=0;j<2;j++){
ArrayList<Integer> list=new ArrayList<Integer>();
for(int i=5;i>0;i--){
list.add(i);
}
lists.add(list);
}
System.out.println("Before");
printLists(lists);
processLists(lists);
System.out.println("\nAfter");
printLists(lists);
}
public static void processLists(ArrayList<ArrayList<Integer>> list){
ArrayList<ArrayList<Integer>> myTrace=new ArrayList<ArrayList<Integer>>(list);
//myTrace.addAll(list);
for(int j=0;j<myTrace.size();j++){
myTrace.get(j).remove(myTrace.get(j).size()-1); //remove last element in the inner lists
}
System.out.println("\nInside");
printLists(myTrace);
}
public static void printLists(ArrayList<ArrayList<Integer>> lists){
for(int i=0;i<lists.size();i++){
for(int j=0;j<lists.get(i).size();j++){
System.out.print(lists.get(i).get(j)+" ");
}
System.out.println();
}
}
}
Suppose the above code generates output as:
Before: 5 4 3 2 1 \n 5 4 3 2 1
Inside: 5 4 3 2 \n 5 4 3 2
After: 5 4 3 2 \n 5 4 3 2
Here, processLists method is changing the original contents of 'lists'. How to restrict this modification? I've tried with the solutions mentioned in the link. Though it works with single ArrayList, but not with ArrayList of ArrayList.
The article you link to says to make and pass a copy of the list, so that the original can't be changed. The same technique can be applied here, but you have to copy everything.
When you say
ArrayList<T> a = new ArrayList<T> (b);
it will create a new ArrayList with a copy of the data from b. However, although a new ArrayList is created, it does not copy the objects that the elements refer to. Thus, each element of a will refer to the same object as the corresponding element of b.
Thus, in particular:
ArrayList<ArrayList<Integer>> myTrace = new ArrayList<ArrayList<Integer>>(list);
only creates one new ArrayList. It does not make copies of all the ArrayList<Integer> elements. Thus, after the above, myTrace.get(0) == list.get(0) will be true because they are the same reference [if the lists aren't empty]. And if you do something that modifies an element, the modification will show up in both:
myTrace.get(n).set(x,y)
will also affect the ArrayList<Integer> referred to by list.get(n), because myTrace.get(n) and list.get(n) will return the same reference.
You'll need a loop to copy the arrays:
ArrayList<ArrayList<Integer>> myTrace = new ArrayList<ArrayList<Integer>>();
for (ArrayList<Integer> sublist : list) {
myTrace.add(new ArrayList<Integer>(sublist)); // makes a copy of the sublist
}
or use a stream in Java 8:
ArrayList<ArrayList<Integer>> myTrace = new ArrayList<> (
list.stream().map(ArrayList::new).collect(Collectors.toList()));

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

Addressing multi-dimensional arraylists

I'm attempting a radix sort but I'm having trouble addressing arraylists of arraylists. The list has 10 spaces, each with a bucket of size n.
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>(10);
ArrayList<Integer> bucket = new ArrayList<>();
bucket.add(99);
list.add(bucket);
list.add(bucket);
list.get(0).add(12); (6)
When I attempt to add in a value using (6) it adds 12 for each arraylist within list (presumably because they are both buckets). How can I initialize the arraylist properly such that I treat each arraylist in list independently? And would I access the elements of each arraylist in list in a similar fashion?
I think what you're looking for is
for (int i = 0; i < 10; i++) {
list.add(new ArrayList<>());
}
You can set a size for each bucket if you want also - I think by passing the desired size to the ArrayList constructor
When you add 12 to the ArrayList in list, you are adding to a referenced ArrayList, which in this case is bucket. list.get(0) and list.get(1) will both return a reference to the same ArrayList, bucket.

Categories

Resources