JavaUsing ArrayList versus HashMap in Java

Using ArrayList versus HashMap in Java

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Java ArrayList and HashMap tutorial

Performance is a key consideration when your applications begin to grow larger in size. Most developers do not realize that our usage of Java collections, including ArrayList and HashMap can provide remarkable differences in terms of resource utilization and application speed in the long run. The below Java code snippet illustrates the difference between these Java collections when they re run for a considerable time.

Read more Java tutorials.

Here is a code example showing how to use ArrayList and HashMap in Java:

*/

import java.util.*;

public class ArrayListVsHashMap
{
	public static void main(String args[])
	{
		ArrayListVsHashMap arrayListVsHashMap = new ArrayListVsHashMap();
		arrayListVsHashMap.proceed();
	}
	
	private void proceed()
	{
		String searchString = "Four";
		boolean found = false;
		long startTime, endTime;
		int loopCount = 100000000;

		ArrayList arrayList = new ArrayList();
		
		arrayList.add("One");
		arrayList.add("Two");
		arrayList.add("Three");
		arrayList.add("Four");
		arrayList.add("Five");
		
		startTime = System.currentTimeMillis();
		for (int i = 0; i < loopCount; i++)
		{
			found = arrayList.contains(searchString);
			
		}
		endTime = System.currentTimeMillis();
		System.out.println("Total time for ArrayList: " + (endTime - startTime) );

		HashMap hashMap = new HashMap();
		
		hashMap.put("One","One");
		hashMap.put("Two","Two");
		hashMap.put("Three","Three");
		hashMap.put("Four","Four");
		hashMap.put("Five","Five");
		
		startTime = System.currentTimeMillis();
		for (int i = 0; i < loopCount; i++)
		{
			found = hashMap.containsKey(searchString);
			
		}
		endTime = System.currentTimeMillis();
		System.out.println("Total time for HashMap: " + (endTime - startTime) );
	}
}

/*

Note: These output of this Java code when run in your integrated development environment (IDE) or code editor may differ based on multiple parameters. You can, however, expect output similar to the following:

[root@mypc]# java ArrayListVsHashMap
Total time for ArrayList: 562
Total time for HashMap: 459

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories