BufBills
BufBills

Reputation: 8103

Do I need to new ArrayList in loop every time?

Here, I created a new 2D ArrayList and sort it.

//1. sort list, based on col 0.
//list : List<List<Integer>>
List<ArrayList<Integer>> sortedList = new ArrayList<ArrayList<Integer>>();
for(int i = 0; i < list.size(); i++){
    sortedList.add(new ArrayList<Integer>(list.get(i))); //===> question for this line!
}

Collections.sort(sortedList, new Comparator<ArrayList<Integer>>() {    
        @Override
        public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) {
            return o1.get(0).compareTo(o2.get(0));
        }               
});

I have a question, for my question line. (see arrow above), do I need to "new" it as I did, or I can just call

sortedList.add(list.get(i));

Upvotes: 0

Views: 628

Answers (2)

niven hyde
niven hyde

Reputation: 1

Based on your program above,you declared sortedList as a list of arraylists: List> sortedList = new ArrayList>()

SortedList will expect a new ArrayList of type Integer or a reference of ArrayList of type integers

If you want your sortedList to contain a new Array List of Integers for each iteration do the following;

for(int I=0 I<Iist.size I++){
    List<Integer> ints = new ArrayList<Integer>();
    ints.add(list(I));
    sortedList.add(ints);

}

If you want your sortedList to contain only reference of ArrayList of Integers do the following: Asssuming the list object you are iterating over is of type ArrayList,you can just do sortedList.add(list)

Upvotes: 0

Turakar
Turakar

Reputation: 190

The difference between your two approaches are in the way of how the references are. In general both should work.

In your first approach you have created a copy of the 2D list, meaning changes to the old list would not affect your sorted list. The first way is more secure.

In your second approach you have created a shallow copy of the 2D list, meaning if you would change a sub list of your sorted list, these changes would affect the original list and the other way around. The second way is more memory efficient and faster.

Upvotes: 1

Related Questions