What is an efficient way to reuse ArrayLists in a for loop?

I reuse the same ArrayList in a for loop, and I use

for loop
    results = new ArrayList<Integer>();
    experts = new ArrayList<Integer>();
    output = new ArrayList<String>();
....

to create new ones.

I guess this is wrong because I allocate new memory. It's right? If so, how can I delete them?

Added: another example

I create new variables every time I call this method. Is this a good practice? I want to create a new precision matching the found .. etc? Or should I declare them in my class, do not allocate more and more memory outside the method?

public static void computeMAP(ArrayList<Integer> results, ArrayList<Integer> experts) {

  //compute MAP
  double precision = 0;
  int relevantFound = 0;
  double sumprecision = 0;

thank

+3
source share
5 answers

ArrayList.clear() ; , - "", Java , . , ( ), clear .

, ; ( , ), . (.. new), .

:
, , . , new "" ; - - , , , , - .
, - ; , , , , - .

+7

-, java, .

, . 100k, , 3 . List.clear().

, . , , 256 64 .

, , . . , Android for (int = 0...) (Object o: someList). , . , clear() .

+1

, clear() .

, . , .

, 100 000 . . .

:

Elapsed time - in the loop: 2198 
Elapsed time - with clear(): 1621

Elapsed time - in the loop: 2291 
Elapsed time - with clear(): 1621   

Elapsed time - in the loop: 2182 
Elapsed time - with clear(): 1605

, , . , , .

: Java 1.6.0_19, Centrino 2 Windows. , .

import java.util.*;

public class Main {
    public static void main(String[] args)    {

      // Allocates a new list inside the loop
      long startTime = System.currentTimeMillis();
      for( int i = 0; i < 100000; i++ ) {
         List<String> l1 = new ArrayList<String>();
         for( int j = 0; j < 1000; j++ )
            l1.add( "test" );
      }
      System.out.println( "Elapsed time - in the loop: " + (System.currentTimeMillis() - startTime) );

      // Reuse the list
      startTime = System.currentTimeMillis();
      List<String> l2 = new ArrayList<String>();
      for( int i = 0; i < 100000; i++ ) {
         l2.clear();
         for( int j = 0; j < 1000; j++ )
            l2.add( "test" );
      }
      System.out.println( "Elapsed time - with clear(): " + (System.currentTimeMillis() - startTime) );
    }
}
+1

ArrayLists 5 . , 4 ( , , 8 ). int "" , 24 . 16 , ( ), 40 ArrayList(). , , .

, , Java 1.6.16, JVM ( ?), "" , . "" , .

0

, , - , . , ArrayList ArrayList.clear() .

, , , "" "" . , - (.. ). (. ).

, , , , . , , .

0

Source: https://habr.com/ru/post/1744697/


All Articles