Title: Java ArrayList - How to use (with video) - Examples Java Code Geeks
Open Graph Title: Java ArrayList - How to use (with video) - Examples Java Code Geeks
Description: The ArrayList class in Java supports only object types & not primitive types. Its methods are mostly used to add, remove elements in a list.
Open Graph Description: The ArrayList class in Java supports only object types & not primitive types. Its methods are mostly used to add, remove elements in a list.
Mail addresses
support@javacodegeeks.com
Opengraph URL: https://examples.javacodegeeks.com/arraylist-java-example/
Generator: WordPress 6.9.4
Domain: examples.javacodegeeks.com
{"@context":"https://schema.org","@graph":[{"@type":"Article","@id":"https://examples.javacodegeeks.com/arraylist-java-example/#article","isPartOf":{"@id":"https://examples.javacodegeeks.com/arraylist-java-example/"},"author":{"name":"Konstantina Dimtsa","@id":"https://examples.javacodegeeks.com/#/schema/person/5fc06d4d50814931c15af68106832a56"},"headline":"Java ArrayList Example – How to use ArrayList (with video)","datePublished":"2013-12-30T10:00:59+00:00","dateModified":"2022-07-05T20:28:54+00:00","mainEntityOfPage":{"@id":"https://examples.javacodegeeks.com/arraylist-java-example/"},"wordCount":881,"commentCount":1,"publisher":{"@id":"https://examples.javacodegeeks.com/#organization"},"image":{"@id":"https://examples.javacodegeeks.com/arraylist-java-example/#primaryimage"},"thumbnailUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","keywords":["featured"],"articleSection":["ArrayList"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https://examples.javacodegeeks.com/arraylist-java-example/#respond"]}]},{"@type":"WebPage","@id":"https://examples.javacodegeeks.com/arraylist-java-example/","url":"https://examples.javacodegeeks.com/arraylist-java-example/","name":"Java ArrayList - How to use (with video) - Examples Java Code Geeks","isPartOf":{"@id":"https://examples.javacodegeeks.com/#website"},"primaryImageOfPage":{"@id":"https://examples.javacodegeeks.com/arraylist-java-example/#primaryimage"},"image":{"@id":"https://examples.javacodegeeks.com/arraylist-java-example/#primaryimage"},"thumbnailUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","datePublished":"2013-12-30T10:00:59+00:00","dateModified":"2022-07-05T20:28:54+00:00","description":"The ArrayList class in Java supports only object types & not primitive types. Its methods are mostly used to add, remove elements in a list.","breadcrumb":{"@id":"https://examples.javacodegeeks.com/arraylist-java-example/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https://examples.javacodegeeks.com/arraylist-java-example/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/arraylist-java-example/#primaryimage","url":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","width":150,"height":150,"caption":"Bipartite Graph"},{"@type":"BreadcrumbList","@id":"https://examples.javacodegeeks.com/arraylist-java-example/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://examples.javacodegeeks.com/"},{"@type":"ListItem","position":2,"name":"Java Development","item":"https://examples.javacodegeeks.com/category/java-development/"},{"@type":"ListItem","position":3,"name":"Core Java","item":"https://examples.javacodegeeks.com/category/java-development/core-java/"},{"@type":"ListItem","position":4,"name":"util","item":"https://examples.javacodegeeks.com/category/java-development/core-java/util/"},{"@type":"ListItem","position":5,"name":"ArrayList","item":"https://examples.javacodegeeks.com/category/java-development/core-java/util/arraylist/"},{"@type":"ListItem","position":6,"name":"Java ArrayList Example – How to use ArrayList (with video)"}]},{"@type":"WebSite","@id":"https://examples.javacodegeeks.com/#website","url":"https://examples.javacodegeeks.com/","name":"Java Code Geeks","description":"Java Examples and Code Snippets","publisher":{"@id":"https://examples.javacodegeeks.com/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://examples.javacodegeeks.com/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https://examples.javacodegeeks.com/#organization","name":"Exelixis Media P.C.","url":"https://examples.javacodegeeks.com/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/#/schema/logo/image/","url":"https://examples.javacodegeeks.com/wp-content/uploads/2022/06/exelixis-logo.png","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2022/06/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https://examples.javacodegeeks.com/#/schema/logo/image/"},"sameAs":["https://www.facebook.com/javacodegeeks","https://x.com/javacodegeeks"]},{"@type":"Person","@id":"https://examples.javacodegeeks.com/#/schema/person/5fc06d4d50814931c15af68106832a56","name":"Konstantina Dimtsa","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/#/schema/person/image/","url":"https://examples.javacodegeeks.com/wp-content/uploads/2013/10/Konstantina-Dimtsa-96x96.jpg","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2013/10/Konstantina-Dimtsa-96x96.jpg","caption":"Konstantina Dimtsa"},"description":"Konstantina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she is currently pursuing M.Sc studies in Advanced Information Systems at the same department. She is also working as a research associate for NKUA in the field of telecommunications. Her main interests lie in software engineering, web applications, databases and telecommunications.","sameAs":["http://www.javacodegeeks.com"],"url":"https://examples.javacodegeeks.com/author/konstantina-dimtsa/"}]}
{"@context":"http:\/\/schema.org","@type":"BreadcrumbList","@id":"#Breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"item":{"name":"Home","@id":"https:\/\/examples.javacodegeeks.com\/"}},{"@type":"ListItem","position":2,"item":{"name":"Java Development","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/"}},{"@type":"ListItem","position":3,"item":{"name":"Core Java","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/"}},{"@type":"ListItem","position":4,"item":{"name":"util","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/util\/"}},{"@type":"ListItem","position":5,"item":{"name":"ArrayList","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/util\/arraylist\/"}}]}
{"@context":"http:\/\/schema.org","@type":"Article","dateCreated":"2013-12-30T12:00:59+02:00","datePublished":"2013-12-30T12:00:59+02:00","dateModified":"2022-07-05T23:28:54+03:00","headline":"Java ArrayList Example – How to use ArrayList (with video)","name":"Java ArrayList Example – How to use ArrayList (with video)","keywords":"featured","url":"https:\/\/examples.javacodegeeks.com\/arraylist-java-example\/","description":"In this example, we will show how to use ArrayList in Java. The class java.util.ArrayList provides a resizable array, which means that items can be added and removed from the list by using the provide","copyrightYear":"2013","articleSection":"ArrayList","articleBody":"\nIn this example, we will show how to use ArrayList in Java. \n\n\n\nThe class java.util.ArrayList provides a resizable array, which means that items can be added and removed from the list by using the provided ArrayList methods. It implements the List interface.\n\n\n\nA major question related to arraylists is about when to use them instead of arrays and vice versa. An ArrayList is a dynamic data structure so it can be used when there is no upper bound on the number of elements.\n\n\n\nFrom the other side, a simple Array in java is a static data structure, because the initial size of an array cannot be changed, so it can be used only when the data has a known number of elements.\n\n\n\nYou can also check this tutorial in the following video: \n\n\n\n ArrayList Java Example - How to use ArrayList - Video\n\n\n\n1. ArrayList Java Constructors\n\n\n\nThe ArrayList class supports three constructors.\n\n\n\nArraylist()This constructor builds an empty list.ArrayList(Collection<? extends E> c)This constructor creates a list containing the elements of the specified collection. Note that E is the notation for the type of an element in a collection.ArrayList(int initialCapacity)This constructor creates an empty list with the specified initial capacity.\n\n\n\nFor example, if you want to create an empty array list of Strings then you would do the following:\n\n\n\nArrayList<String> list = new ArrayList<String>(); \n\n\n\nIf you want to create an array list with initial capacity, then you should do the following:\n\n\n\nArrayList<Integer> list = new ArrayList<Integer>(7);\n\n\n\nNote: ArrayList class supports only object types and not primitive types.\n\n\n\n2. ArrayList methods\n\n\n\nHere are some of the most useful ArrayList methods:\n\n\n\nAdding elements to the list\n\nboolean add(Element e)Adds the specified element to the end of this list.\n\nvoid add(int index, Element e)Adds the specified element at the specified position in the list.\n\n\nRemoving elements from the list\n\nvoid clear()Removes all the elements from the list.\n\nE remove(int index)Removes the element at the specified position in the list.\n\nprotected void removeRange(int start, int end)Removes from the list all the elements starting from index start (included) until index end (not included).\n\n\n\nGetting elements from the list\n\nE get(int index)Returns the element at the specified position.\n\nObject[] toArray()Returns an array containing all the elements of the list in proper sequence.\n\n\nSetting an element\n\nE set(int index, E element)Replaces the element at the specified position with the specified element.\n\nSearching elements\n\nboolean contains(Object o)Returns true if the specified element is found in the list.\n\nint indexOf(Object o)Returns the index of the first occurrence of the specified element in the list. If this element is not in the list, the method returns -1.\n\nint lastIndexOf(Object o)Returns the index of the last occurrence of the specified element in the list. If this element is not in the list, the method returns -1.\n\n\n\nIterating the arraylist\n\nIterator iterator()Returns an iterator over the elements in the list.\n\nListIterator listIterator()Returns a list iterator over the elements in this list.\n\n\nChecking if the list is empty\n\nboolean isEmpty()Returns true if the list does not contain any element.\n\nGetting the size of the list\n\nint size()Returns the length of the list (the number of elements contained in the list).\n\n\n\n\n\nThose were the most commonly used ArrayList methods. For further details for each method or for other methods that are not mentioned in this section, you can have a look at the official Java API.\n\n\n\n3. Examples of using ArrayList in Java\n\n\n\nArrayList, LinkedList, Vector, and Stack implement the List interface. \n\n\n\nFigure 1 ArrayList\n\n\n\nIn this step, I will create five Junit test classes to show the usages of ArrayList as well as LinkedList, Vector, and Stack.\n\n\n\nI will include both Junit and Logback libraries in the pom.xml file.\n\n\n\npom.xml\n\n\n\n\n<project xmlns=\"http:\/\/maven.apache.org\/POM\/4.0.0\"\n\txmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\"\n\txsi:schemaLocation=\"http:\/\/maven.apache.org\/POM\/4.0.0 http:\/\/maven.apache.org\/xsd\/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0<\/modelVersion>\n\t<groupId>jcg.zheng.demo<\/groupId>\n\t<artifactId>java-arraylist-demo<\/artifactId>\n\t<version>0.0.1-SNAPSHOT<\/version>\n\t<build>\n\t\t<sourceDirectory>src<\/sourceDirectory>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-compiler-plugin<\/artifactId>\n\t\t\t\t<version>3.8.0<\/version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<release>11<\/release>\n\t\t\t\t<\/configuration>\n\t\t\t<\/plugin>\n\t\t<\/plugins>\n\t<\/build>\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>junit<\/groupId>\n\t\t\t<artifactId>junit<\/artifactId>\n\t\t\t<version>4.12<\/version>\n\t\t<\/dependency>\n\t\t<dependency>\n\t\t\t<groupId>ch.qos.logback<\/groupId>\n\t\t\t<artifactId>logback-access<\/artifactId>\n\t\t\t<version>1.2.3<\/version>\n\t\t<\/dependency>\n\t\t<dependency>\n\t\t\t<groupId>ch.qos.logback<\/groupId>\n\t\t\t<artifactId>logback-classic<\/artifactId>\n\t\t\t<version>1.2.3<\/version>\n\t\t<\/dependency>\n\t\t<dependency>\n\t\t\t<groupId>ch.qos.logback<\/groupId>\n\t\t\t<artifactId>logback-core<\/artifactId>\n\t\t\t<version>1.2.3<\/version>\n\t\t<\/dependency>\n\t<\/dependencies>\n<\/project>\n\n\n\n3.1 ListBaseTest\n\n\n\nCreate a JUnit class named ListBaseTest.java with the following code:\n\n\n\nListBaseTest.java\n\n\n\npackage jcg.zheng.demo;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertFalse;\nimport static org.junit.Assert.assertTrue;\n\nimport java.util.Arrays;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.junit.FixMethodOrder;\nimport org.junit.Test;\nimport org.junit.runners.MethodSorters;\nimport org.slf4j.Logger;\n\n@FixMethodOrder(MethodSorters.NAME_ASCENDING)\npublic abstract class ListBaseTest {\n\n\tprotected Logger logger;\n\n\tList<String> list;\n\n\t@Test\n\tpublic void test_add() {\n\t\t\/\/ Adding items to arrayList\n\t\tlist.add(\"new Item\");\n\t\tassertEquals(5, list.size());\n\n\t\t\/\/ Display the contents of the array list\n\t\tlogger.info(\"The arraylist contains the following elements: \" + list);\n\t}\n\n\t@Test\n\tpublic void test_contains() {\n\t\t\/\/ Checking if an element is included to the list\n\t\tassertTrue(list.contains(\"Item1\"));\n\t\tassertFalse(list.contains(\"Item5\"));\n\t}\n\n\t@Test\n\tpublic void test_get() {\n\t\tassertEquals(\"Item1\", list.get(0));\n\t\tassertEquals(\"Item2\", list.get(1));\n\t\tassertEquals(\"Item3\", list.get(2));\n\t\tassertEquals(\"Item4\", list.get(3));\n\t}\n\n\t@Test\n\tpublic void test_getSize() {\n\t\t\/\/ Getting the size of the list\n\t\tassertEquals(4, list.size());\n\t}\n\n\t@Test\n\tpublic void test_indexOf() {\n\t\t\/\/ Checking index of an item\n\t\tint pos = list.indexOf(\"Item2\");\n\t\tassertEquals(1, pos);\n\t}\n\n\t@Test\n\tpublic void test_isEmpty() {\n\t\t\/\/ Checking if array list is empty\n\t\tassertFalse(list.isEmpty());\n\t}\n\n\t@Test\n\tpublic void test_loop_arraylist_via_for() {\n\t\t\/\/ Retrieve elements from the arraylist via foreach\n\t\tlogger.info(\"Retrieving items using foreach loop\");\n\t\tfor (String str : list) {\n\t\t\tlogger.info(\"Item is: \" + str);\n\t\t}\n\t}\n\n\t@Test\n\tpublic void test_loop_arraylist_via_for_2() {\n\t\t\/\/ Retrieve elements from the arraylist via loop using index and size list\n\t\tlogger.info(\"Retrieving items with loop using index and size list\");\n\t\tfor (int i = 0; i < list.size(); i++) {\n\t\t\tlogger.info(\"Index: \" + i + \" - Item: \" + list.get(i));\n\t\t}\n\t}\n\n\t@Test\n\tpublic void test_loop_arrayList_via_foreach() {\n\t\tlogger.info(\"Retrieving items using Java 8 Stream\");\n\t\tlist.forEach((item) -> {\n\t\t\tlogger.info(item);\n\t\t});\n\t}\n\n\t@Test\n\tpublic void test_loop_arraylist_via_iterator_for() {\n\t\t\/\/ hasNext(): returns true if there are more elements\n\t\t\/\/ next(): returns the next element\n\t\tlogger.info(\"Retrieving items using iterator\");\n\t\tfor (Iterator<String> it = list.iterator(); it.hasNext();) {\n\t\t\tlogger.info(\"Item is: \" + it.next());\n\t\t}\n\t}\n\n\t@Test\n\tpublic void test_loop_arraylist_via_iterator_while() {\n\t\tIterator<String> it = list.iterator();\n\t\tlogger.info(\"Retrieving items using iterator\");\n\t\twhile (it.hasNext()) {\n\t\t\tlogger.info(\"Item is: \" + it.next());\n\t\t}\n\t}\n\n\t@Test\n\tpublic void test_remove() {\n\t\t\/\/ removing the item in index 0\n\t\tlist.remove(0);\n\t\tassertEquals(3, list.size());\n\t\tassertEquals(\"Item2\", list.get(0));\n\t\tassertEquals(\"Item3\", list.get(1));\n\t\tassertEquals(\"Item4\", list.get(2));\n\n\t\t\/\/ removing the first occurrence of item \"Item3\"\n\t\tlist.remove(\"Item3\");\n\t\tassertEquals(2, list.size());\n\t\tassertEquals(\"Item2\", list.get(0));\n\t\tassertEquals(\"Item4\", list.get(1));\n\t}\n\n\t@Test\n\tpublic void test_replace() {\n\t\t\/\/ Replacing an element\n\t\tlist.set(1, \"NewItem\");\n\t\tassertEquals(\"Item1\", list.get(0));\n\t\tassertEquals(\"NewItem\", list.get(1));\n\t\tassertEquals(\"Item3\", list.get(2));\n\t\tassertEquals(\"Item4\", list.get(3));\n\t}\n\n\t@Test\n\tpublic void test_toArray() {\n\t\t\/\/ Converting ArrayList to Array\n\t\tString[] simpleArray = list.toArray(new String[list.size()]);\n\t\tlogger.info(\"The array created after the conversion of our arraylist is: \" + Arrays.toString(simpleArray));\n\t}\n}\n\n\n\nIn the above code, we can see that many List usage cases are covered. Adding elements to the list using two different methods, removing elements, getting the size of the list, checking if the list is empty, checking if a specific element is contained to the list. Also, five different ways are presented for retrieving the elements of a list. Finally, we show how to convert an List to Array.\n\n\n\n3.2 ArrayListTest\n\n\n\nCreate a JUnit class named ArrayListTest.java.\n\n\n\nArrayListTest.java\n\n\n\npackage jcg.zheng.demo;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertTrue;\n\nimport java.util.ArrayList;\n\nimport org.junit.Before;\nimport org.slf4j.LoggerFactory;\n\npublic class ArrayListTest extends ListBaseTest {\t\n\n\t@Before\n\tpublic void setup_list_with_4_items() {\n\t\tlogger = LoggerFactory.getLogger(this.getClass());\n\t\t\n\t\t\/\/ Creating an empty array list\n\t\tlist = new ArrayList<String>();\n\t\tassertTrue(list.isEmpty());\n\n\t\t\/\/ Adding items to arrayList\n\t\tlist.add(\"Item1\");\n\t\tassertEquals(1, list.size());\n\t\tlist.add(\"Item2\");\n\t\tassertEquals(2, list.size());\n\t\tlist.add(2, \"Item3\"); \/\/ add Item3 to the third position of array list\n\t\tassertEquals(3, list.size());\n\t\tlist.add(\"Item4\");\n\t\tassertEquals(4, list.size());\n\t}\n\n}\n\n\n\n\nExecute mvn test -Dtest=ArrayListTest and capture output.\n\n\n\nOutput\n\n\n\nRunning jcg.zheng.demo.ArrayListTest\n16:01:02.294 [main] INFO jcg.zheng.demo.ArrayListTest - The arraylist contains the following elements: [Item1, Item2, Item3, Item4, new Item]\n16:01:02.308 [main] INFO jcg.zheng.demo.ArrayListTest - Retrieving items using Java 8 Stream\n16:01:02.310 [main] INFO jcg.zheng.demo.ArrayListTest - Item1\n16:01:02.310 [main] INFO jcg.zheng.demo.ArrayListTest - Item2\n16:01:02.310 [main] INFO jcg.zheng.demo.ArrayListTest - Item3\n16:01:02.310 [main] INFO jcg.zheng.demo.ArrayListTest - Item4\n16:01:02.311 [main] INFO jcg.zheng.demo.ArrayListTest - Retrieving items using foreach loop\n16:01:02.315 [main] INFO jcg.zheng.demo.ArrayListTest - Item is: Item1\n16:01:02.315 [main] INFO jcg.zheng.demo.ArrayListTest - Item is: Item2\n16:01:02.315 [main] INFO jcg.zheng.demo.ArrayListTest - Item is: Item3\n16:01:02.315 [main] INFO jcg.zheng.demo.ArrayListTest - Item is: Item4\n16:01:02.318 [main] INFO jcg.zheng.demo.ArrayListTest - Retrieving items with loop using index and size list\n16:01:02.352 [main] INFO jcg.zheng.demo.ArrayListTest - Index: 0 - Item: Item1\n16:01:02.352 [main] INFO jcg.zheng.demo.ArrayListTest - Index: 1 - Item: Item2\n16:01:02.352 [main] INFO jcg.zheng.demo.ArrayListTest - Index: 2 - Item: Item3\n16:01:02.352 [main] INFO jcg.zheng.demo.ArrayListTest - Index: 3 - Item: Item4\n16:01:02.353 [main] INFO jcg.zheng.demo.ArrayListTest - Retrieving items using iterator\n16:01:02.354 [main] INFO jcg.zheng.demo.ArrayListTest - Item is: Item1\n16:01:02.354 [main] INFO jcg.zheng.demo.ArrayListTest - Item is: Item2\n16:01:02.354 [main] INFO jcg.zheng.demo.ArrayListTest - Item is: Item3\n16:01:02.354 [main] INFO jcg.zheng.demo.ArrayListTest - Item is: Item4\n16:01:02.356 [main] INFO jcg.zheng.demo.ArrayListTest - Retrieving items using iterator\n16:01:02.357 [main] INFO jcg.zheng.demo.ArrayListTest - Item is: Item1\n16:01:02.358 [main] INFO jcg.zheng.demo.ArrayListTest - Item is: Item2\n16:01:02.358 [main] INFO jcg.zheng.demo.ArrayListTest - Item is: Item3\n16:01:02.358 [main] INFO jcg.zheng.demo.ArrayListTest - Item is: Item4\n16:01:02.363 [main] INFO jcg.zheng.demo.ArrayListTest - The array created after the conversion of our arraylist is: [Item1, Item2, Item3, Item4]\nTests run: 14, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.486 sec\n\nResults :\n\nTests run: 14, Failures: 0, Errors: 0, Skipped: 0\n\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 11.663 s\n[INFO] Finished at: 2019-07-26T16:01:02-05:00\n[INFO] ------------------------------------------------------------------------\n\nC:\\MaryZheng\\Workspaces\\jdk12\\java-arraylist-demo>mvn test -Dtest=ArrayListTest\n\n\n\nAs we see in the output, the results are complied with what we described in the previous section. \n\n\n\n3.3 LinkedListTest\n\n\n\nCreate a JUnit class named LinkedListTest.java.\n\n\n\nLinkedListTest.java\n\n\n\npackage jcg.zheng.demo;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertTrue;\n\nimport java.util.LinkedList;\n\nimport org.junit.Before;\nimport org.slf4j.LoggerFactory;\n\npublic class LinkedListTest extends ListBaseTest {\n\n\t@Before\n\tpublic void setup_list_with_4_items() {\n\t\tlogger = LoggerFactory.getLogger(this.getClass());\n\t\t\n\t\t\/\/ Creating an empty linked list\n\t\tlist = new LinkedList<String>();\n\t\tassertTrue(list.isEmpty());\n\n\t\t\/\/ Adding items to arrayList\n\t\tlist.add(\"Item1\");\n\t\tassertEquals(1, list.size());\n\t\tlist.add(\"Item2\");\n\t\tassertEquals(2, list.size());\n\t\tlist.add(2, \"Item3\"); \/\/ add Item3 to the third position of array list\n\t\tassertEquals(3, list.size());\n\t\tlist.add(\"Item4\");\n\t\tassertEquals(4, list.size());\n\t}\n\n}\n\n\n\n\nExecute mvn test -Dtest=LinkedListTest and capture output.\n\n\n\nOutput\n\n\n\nRunning jcg.zheng.demo.LinkedListTest\n16:03:20.954 [main] INFO jcg.zheng.demo.LinkedListTest - The arraylist contains the following elements: [Item1, Item2, Item3, Item4, new Item]\n16:03:20.967 [main] INFO jcg.zheng.demo.LinkedListTest - Retrieving items using Java 8 Stream\n16:03:20.968 [main] INFO jcg.zheng.demo.LinkedListTest - Item1\n16:03:20.968 [main] INFO jcg.zheng.demo.LinkedListTest - Item2\n16:03:20.968 [main] INFO jcg.zheng.demo.LinkedListTest - Item3\n16:03:20.969 [main] INFO jcg.zheng.demo.LinkedListTest - Item4\n16:03:20.969 [main] INFO jcg.zheng.demo.LinkedListTest - Retrieving items using foreach loop\n16:03:20.970 [main] INFO jcg.zheng.demo.LinkedListTest - Item is: Item1\n16:03:20.971 [main] INFO jcg.zheng.demo.LinkedListTest - Item is: Item2\n16:03:20.971 [main] INFO jcg.zheng.demo.LinkedListTest - Item is: Item3\n16:03:20.971 [main] INFO jcg.zheng.demo.LinkedListTest - Item is: Item4\n16:03:20.976 [main] INFO jcg.zheng.demo.LinkedListTest - Retrieving items with loop using index and size list\n16:03:21.015 [main] INFO jcg.zheng.demo.LinkedListTest - Index: 0 - Item: Item1\n16:03:21.015 [main] INFO jcg.zheng.demo.LinkedListTest - Index: 1 - Item: Item2\n16:03:21.015 [main] INFO jcg.zheng.demo.LinkedListTest - Index: 2 - Item: Item3\n16:03:21.016 [main] INFO jcg.zheng.demo.LinkedListTest - Index: 3 - Item: Item4\n16:03:21.017 [main] INFO jcg.zheng.demo.LinkedListTest - Retrieving items using iterator\n16:03:21.017 [main] INFO jcg.zheng.demo.LinkedListTest - Item is: Item1\n16:03:21.018 [main] INFO jcg.zheng.demo.LinkedListTest - Item is: Item2\n16:03:21.018 [main] INFO jcg.zheng.demo.LinkedListTest - Item is: Item3\n16:03:21.018 [main] INFO jcg.zheng.demo.LinkedListTest - Item is: Item4\n16:03:21.020 [main] INFO jcg.zheng.demo.LinkedListTest - Retrieving items using iterator\n16:03:21.022 [main] INFO jcg.zheng.demo.LinkedListTest - Item is: Item1\n16:03:21.022 [main] INFO jcg.zheng.demo.LinkedListTest - Item is: Item2\n16:03:21.022 [main] INFO jcg.zheng.demo.LinkedListTest - Item is: Item3\n16:03:21.022 [main] INFO jcg.zheng.demo.LinkedListTest - Item is: Item4\n16:03:21.026 [main] INFO jcg.zheng.demo.LinkedListTest - The array created after the conversion of our arraylist is: [Item1, Item2, Item3, Item4]\nTests run: 14, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.492 sec\n\nResults :\n\nTests run: 14, Failures: 0, Errors: 0, Skipped: 0\n\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 10.188 s\n[INFO] Finished at: 2019-07-26T16:03:21-05:00\n[INFO] ------------------------------------------------------------------------\n\nC:\\MaryZheng\\Workspaces\\jdk12\\java-arraylist-demo>mvn test -Dtest=LinkedListTest\n\n\n\n3.4 VectorTest\n\n\n\nCreate a JUnit class named VectorTest.java.\n\n\n\nVectorTest.java\n\n\n\npackage jcg.zheng.demo;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertTrue;\n\nimport java.util.Vector;\n\nimport org.junit.Before;\nimport org.slf4j.LoggerFactory;\n\npublic class VectorTest extends ListBaseTest {\n\n\t@Before\n\tpublic void setup_list_with_4_items() {\n\t\tlogger = LoggerFactory.getLogger(this.getClass());\n\t\t\n\t\t\/\/ Creating an empty vector\n\t\tlist = new Vector<String>();\n\t\tassertTrue(list.isEmpty());\n\n\t\t\/\/ Adding items to arrayList\n\t\tlist.add(\"Item1\");\n\t\tassertEquals(1, list.size());\n\t\tlist.add(\"Item2\");\n\t\tassertEquals(2, list.size());\n\t\tlist.add(2, \"Item3\"); \/\/ add Item3 to the third position of array list\n\t\tassertEquals(3, list.size());\n\t\tlist.add(\"Item4\");\n\t\tassertEquals(4, list.size());\n\t}\n\n}\n\n\n\n\nExecute mvn test -Dtest=VectorTest and capture output.\n\n\n\nOutput\n\n\n\nRunning jcg.zheng.demo.VectorTest\n16:05:02.444 [main] INFO jcg.zheng.demo.VectorTest - The arraylist contains the following elements: [Item1, Item2, Item3, Item4, new Item]\n16:05:02.459 [main] INFO jcg.zheng.demo.VectorTest - Retrieving items using Java 8 Stream\n16:05:02.465 [main] INFO jcg.zheng.demo.VectorTest - Item1\n16:05:02.466 [main] INFO jcg.zheng.demo.VectorTest - Item2\n16:05:02.466 [main] INFO jcg.zheng.demo.VectorTest - Item3\n16:05:02.467 [main] INFO jcg.zheng.demo.VectorTest - Item4\n16:05:02.469 [main] INFO jcg.zheng.demo.VectorTest - Retrieving items using foreach loop\n16:05:02.470 [main] INFO jcg.zheng.demo.VectorTest - Item is: Item1\n16:05:02.470 [main] INFO jcg.zheng.demo.VectorTest - Item is: Item2\n16:05:02.470 [main] INFO jcg.zheng.demo.VectorTest - Item is: Item3\n16:05:02.471 [main] INFO jcg.zheng.demo.VectorTest - Item is: Item4\n16:05:02.477 [main] INFO jcg.zheng.demo.VectorTest - Retrieving items with loop using index and size list\n16:05:02.527 [main] INFO jcg.zheng.demo.VectorTest - Index: 0 - Item: Item1\n16:05:02.527 [main] INFO jcg.zheng.demo.VectorTest - Index: 1 - Item: Item2\n16:05:02.528 [main] INFO jcg.zheng.demo.VectorTest - Index: 2 - Item: Item3\n16:05:02.528 [main] INFO jcg.zheng.demo.VectorTest - Index: 3 - Item: Item4\n16:05:02.529 [main] INFO jcg.zheng.demo.VectorTest - Retrieving items using iterator\n16:05:02.530 [main] INFO jcg.zheng.demo.VectorTest - Item is: Item1\n16:05:02.531 [main] INFO jcg.zheng.demo.VectorTest - Item is: Item2\n16:05:02.531 [main] INFO jcg.zheng.demo.VectorTest - Item is: Item3\n16:05:02.531 [main] INFO jcg.zheng.demo.VectorTest - Item is: Item4\n16:05:02.532 [main] INFO jcg.zheng.demo.VectorTest - Retrieving items using iterator\n16:05:02.533 [main] INFO jcg.zheng.demo.VectorTest - Item is: Item1\n16:05:02.534 [main] INFO jcg.zheng.demo.VectorTest - Item is: Item2\n16:05:02.534 [main] INFO jcg.zheng.demo.VectorTest - Item is: Item3\n16:05:02.534 [main] INFO jcg.zheng.demo.VectorTest - Item is: Item4\n16:05:02.537 [main] INFO jcg.zheng.demo.VectorTest - The array created after the conversion of our arraylist is: [Item1, Item2, Item3, Item4]\nTests run: 14, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.632 sec\n\nResults :\n\nTests run: 14, Failures: 0, Errors: 0, Skipped: 0\n\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 10.325 s\n[INFO] Finished at: 2019-07-26T16:05:02-05:00\n[INFO] ------------------------------------------------------------------------\n\nC:\\MaryZheng\\Workspaces\\jdk12\\java-arraylist-demo>mvn test -Dtest=VectorTest\n\n\n\n3.5 StackTest\n\n\n\nCreate a JUnit class named StackTest.java.\n\n\n\nStackTest.java\n\n\n\npackage jcg.zheng.demo;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertTrue;\n\nimport java.util.Stack;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.LoggerFactory;\n\npublic class StackTest extends ListBaseTest {\n\n\t@Before\n\tpublic void setup_list_with_4_items() {\n\t\tlogger = LoggerFactory.getLogger(this.getClass());\n\n\t\t\/\/ Creating an empty vector\n\t\tlist = new Stack<String>();\n\t\tassertTrue(list.isEmpty());\n\n\t\t\/\/ Adding items to arrayList\n\t\tlist.add(\"Item1\");\n\t\tassertEquals(1, list.size());\n\t\tlist.add(\"Item2\");\n\t\tassertEquals(2, list.size());\n\t\tlist.add(2, \"Item3\"); \/\/ add Item3 to the third position of array list\n\t\tassertEquals(3, list.size());\n\t\tlist.add(\"Item4\");\n\t\tassertEquals(4, list.size());\n\t}\n\n\t@Test\n\tpublic void test_pop() {\n\t\tString item = ((Stack<String>) list).pop();\n\t\tassertEquals(\"Item4\", item);\n\t}\n\n\t@Test\n\tpublic void test_push() {\n\t\t((Stack<String>) list).push(\"newValue\");\n\t\tassertEquals(5, list.size());\n\t}\n\n}\n\n\n\n\nExecute mvn test -Dtest=StackTest and capture output.\n\n\n\nOutput\n\n\n\nRunning jcg.zheng.demo.StackTest\n16:06:05.112 [main] INFO jcg.zheng.demo.StackTest - The arraylist contains the following elements: [Item1, Item2, Item3, Item4, new Item]\n16:06:05.125 [main] INFO jcg.zheng.demo.StackTest - Retrieving items using Java 8 Stream\n16:06:05.127 [main] INFO jcg.zheng.demo.StackTest - Item1\n16:06:05.127 [main] INFO jcg.zheng.demo.StackTest - Item2\n16:06:05.127 [main] INFO jcg.zheng.demo.StackTest - Item3\n16:06:05.127 [main] INFO jcg.zheng.demo.StackTest - Item4\n16:06:05.128 [main] INFO jcg.zheng.demo.StackTest - Retrieving items using foreach loop\n16:06:05.129 [main] INFO jcg.zheng.demo.StackTest - Item is: Item1\n16:06:05.129 [main] INFO jcg.zheng.demo.StackTest - Item is: Item2\n16:06:05.129 [main] INFO jcg.zheng.demo.StackTest - Item is: Item3\n16:06:05.129 [main] INFO jcg.zheng.demo.StackTest - Item is: Item4\n16:06:05.130 [main] INFO jcg.zheng.demo.StackTest - Retrieving items with loop using index and size list\n16:06:05.185 [main] INFO jcg.zheng.demo.StackTest - Index: 0 - Item: Item1\n16:06:05.185 [main] INFO jcg.zheng.demo.StackTest - Index: 1 - Item: Item2\n16:06:05.186 [main] INFO jcg.zheng.demo.StackTest - Index: 2 - Item: Item3\n16:06:05.187 [main] INFO jcg.zheng.demo.StackTest - Index: 3 - Item: Item4\n16:06:05.191 [main] INFO jcg.zheng.demo.StackTest - Retrieving items using iterator\n16:06:05.195 [main] INFO jcg.zheng.demo.StackTest - Item is: Item1\n16:06:05.197 [main] INFO jcg.zheng.demo.StackTest - Item is: Item2\n16:06:05.198 [main] INFO jcg.zheng.demo.StackTest - Item is: Item3\n16:06:05.198 [main] INFO jcg.zheng.demo.StackTest - Item is: Item4\n16:06:05.200 [main] INFO jcg.zheng.demo.StackTest - Retrieving items using iterator\n16:06:05.201 [main] INFO jcg.zheng.demo.StackTest - Item is: Item1\n16:06:05.202 [main] INFO jcg.zheng.demo.StackTest - Item is: Item2\n16:06:05.202 [main] INFO jcg.zheng.demo.StackTest - Item is: Item3\n16:06:05.202 [main] INFO jcg.zheng.demo.StackTest - Item is: Item4\n16:06:05.213 [main] INFO jcg.zheng.demo.StackTest - The array created after the conversion of our arraylist is: [Item1, Item2, Item3, Item4]\nTests run: 16, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.612 sec\n\nResults :\n\nTests run: 16, Failures: 0, Errors: 0, Skipped: 0\n\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 10.466 s\n[INFO] Finished at: 2019-07-26T16:06:05-05:00\n[INFO] ------------------------------------------------------------------------\n\nC:\\MaryZheng\\Workspaces\\jdk12\\java-arraylist-demo>mvn test -Dtest=StackTest\n\n\n\n4. Summary\n\n\n\nArrayList is part of Java's collection framework and implements Java's List interface. ArrayList is used to store a dynamically sized collection of elements. Vector and ArrayList both use Array internally as a data structure. The main difference is that Vector's methods are synchronized and ArrayList's methods are not synchronized. Click here for more details.\n\n\n\nThe performance differences between ArrayList and LinkedList are as the following:\n\n\n\nPerformanceremove(int idx)get(int idx)add(E ele) Iterator.remove()Iterator.add(E ele) ArrayList\n O(n) \n \n O(1)\n \n O(1)\n \n O(n)\n \n O(n)\n LinkedList \n O(n)\n \n O(n)\n \n O(1) when index=0\n Else O(n)\n \n O(1)\n \n O(1)\n \n\n\n\n5. Related articles\n\n\n\nJava Collections TutorialJava List ExampleJava Array \u2013 java.util.Arrays ExampleLinkedList Java Example\n\n\n\n6. Download the Source Code\n\n\n\nThis was an ArrayList example in Java.\n\n\n\nDownloadDownload the source code here: ArrayList Java Example \u2013 How to use ArrayList\n\n\n\nLast updated on Jan. 11th, 2022\n\n\n\n\n\n\n\nDon't forget to check out our Academy premium site for advanced Java training!\n","publisher":{"@id":"#Publisher","@type":"Organization","name":"Examples Java Code Geeks","logo":{"@type":"ImageObject","url":"\/wp-content\/uploads\/2013\/05\/JavaCodeGeeks-logo.png"},"sameAs":["https:\/\/feeds.feedburner.com\/examplesjavacodegeeks","https:\/\/www.facebook.com\/javacodegeeks","https:\/\/twitter.com\/javacodegeeks","https:\/\/www.linkedin.com\/groups\/3810709\/","https:\/\/www.youtube.com\/channel\/UCxoUc7Rar2q90Gu0nT2ffuQ","https:\/\/github.com\/javacodegeeks\/"]},"sourceOrganization":{"@id":"#Publisher"},"copyrightHolder":{"@id":"#Publisher"},"mainEntityOfPage":{"@type":"WebPage","@id":"https:\/\/examples.javacodegeeks.com\/arraylist-java-example\/","breadcrumb":{"@id":"#Breadcrumb"}},"author":{"@type":"Person","name":"Konstantina Dimtsa","url":"https:\/\/examples.javacodegeeks.com\/author\/konstantina-dimtsa\/"},"image":{"@type":"ImageObject","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","width":1200,"height":150}}
| og:locale | en_US |
| og:type | article |
| og:site_name | Examples Java Code Geeks |
| article:publisher | https://www.facebook.com/javacodegeeks |
| article:published_time | 2013-12-30T10:00:59+00:00 |
| article:modified_time | 2022-07-05T20:28:54+00:00 |
| og:image | https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg |
| og:image:width | 150 |
| og:image:height | 150 |
| og:image:type | image/jpeg |
| author | Konstantina Dimtsa |
| twitter:card | summary_large_image |
| twitter:creator | @javacodegeeks |
| twitter:label1 | Written by |
| twitter:data1 | Konstantina Dimtsa |
| twitter:label2 | Est. reading time |
| twitter:data2 | 13 minutes |
| None | IE=edge |
| msapplication-TileImage | https://examples.javacodegeeks.com/wp-content/uploads/2013/05/JavaCodeGeeks-favIcon.png |
Links:
Viewport: width=device-width, initial-scale=1.0
Robots: index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1