Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA fill a temporary Arraylist with objects and then add it into a ArrayList which consists of arrayLists

I iterate through an Array which consists of objects. I want to find certain parts of this array in which the same specific objects follow eachother.

[a,b,c,#,#,#,h,g,a,#,#,s,#.h] --> I want to find #,#,# and #,# (# is the specific object)

I already figured out how to do this: If I find a '#' I will add this object to a temporary ArrayList. If the next object is a '#' too, I will add it aswell, otherwise I clear the tmplist, because it is a single '#'. If the next object is not a # but the tmplist is bigger than 1 i want to add the tmplist to a 2d ArrayList (An ArrayList which consists of ArrayLists) and clear the tmplist so I can find other parts.

Here is my problem: If i do this the the 2d arraylist does not consist of deepcopys of the templists--> The 2d arraylist consist of empty lists, because I clear the tmplist after every found "pattern". How can I fix this?

Some code which might explain it better:

List<Object> tmplist = new ArrayList<Object>();
   for (int i = 0; i<array.length(); i++) {
       if (array[i].equals(#)) {
          tmplist.add(array[i]);
              if (!array[i+1].equals(#) && tmplist.size() < 2){
                  tmplist.clear();
              } else if (!array[i+1].equals(#) && tmplist.size() > 1) {
                   pattern.add(tmplist);
                   tmplist.clear();
              } 
       }
   }
   //pattern is the 2d ArrayList (ArrayList which consists of ArrayLists)
like image 706
Peter111 Avatar asked Jun 08 '26 07:06

Peter111


2 Answers

if your 2d ArrayList is : result

do

 result.add(new ArrayList<>(tmpList));

By doing this, you are not adding the tmpList itself but a new list with the values of tmpList. So even If you do tmpList.clear() it will not affect the arraylist in your result.

like image 72
Karthik Avatar answered Jun 10 '26 04:06

Karthik


Instead of doing tmplist.clear() do tmplist = new ArrayList<>() so you're working with a different List instance each time.

like image 44
heenenee Avatar answered Jun 10 '26 03:06

heenenee