简体   繁体   中英

How to avoid frequent creation of objects in a loop in java?

eg I have a need where my ArrayList should contain hashmap at each index, eg

Public class Testing {
  private ArrayList < < HashMap< String, String>> myData ;
  public static void main(String[] args) {
    myData = new ArrayList < HashMap < String, String>>();
    initialize();
    //After initialize myData should contain different Hashmaps.
  }
  public static void initialize() {     
    for (int i= 0; i < 10 ;i++) {
      myMap = new HashMap();  //Bad because,creating Objects inside the loop.
      myMap.put("title", "abc"+i); //Adding i, just to show that new values are stored everytime
      myMap.put("name", "xyz"+i);
      myData.add(myMap);
    } 

  }
}

Above code will create hash map objects every time in the loop, what is the better way to do it, so that I can avoid creation of objects every time ? I am using this code in Android , but I think this is more general and related to Java more.

If you need a List of Maps, then that is what you will have to do, there is no way around that. (Actually there is, you could write a helper method that initializes the maps when first accessed and only access the map through that helper method, but I wouldn't really recommend that).

But you could rethink your design and use a different data structure, perhaps turn the Map / List relation around and use a Guava Multimap . That will only initialize the collections when they are needed, and you can save your initialization routine.

Also, a List of Maps can often be replaced by a List of custom objects. Depending on whether the keys are dynamic or not, a custom object may make more sense.

Usually clarity is more important than performance. In this example, having it compile would be an improvement. ;)

You are not creating enough objects to really matter, but one way to reduce its consumption is to use a POJO instead of a HashMap.

I don't think it's bad.

Since you want an ArrayList<<HashMap<String, String>> , there's nothing wrong. Even no bad smell:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM