What is the equivalent way to create a list of objects in Java like the C# way of doing it below (example from the web)? I have to write something in Java, but its new to me. I can’t seem to find what I’m looking for when searching the web either.
List<Author> AuthorList = new List<Author>();
/*The following code snippet creates the Author objects and adds them to the List. */
AuthorList.Add(new Author("Mahesh Chand", 35, "A Prorammer's Guide to ADO.NET", true, new DateTime(2003,7,10))); AuthorList.Add(new Author("Neel Beniwal", 18, "Graphics Development with C#", false, new DateTime(2010, 2, 22))); AuthorList.Add(new Author("Praveen Kumar", 28, "Mastering WCF", true, new DateTime(2012, 01, 01))); AuthorList.Add(new Author("Mahesh Chand", 35, "Graphics Programming with GDI+", true, new DateTime(2008, 01, 20))); AuthorList.Add(new Author("Raj Kumar", 30, "Building Creative Systems", false, new DateTime(2011, 6, 3)));
Answer
In Java, you would just use a generic ArrayList.
import java.util.*; ... ArrayList<Author> AuthorList = new ArrayList<Author>(); AuthorList.add(new Author("Mahesh Chand", 35, "A Prorammer's Guide to ADO.NET", true, java.time.LocalDateTime.of(2003,7,10))); ...
Note that you could type the variable as ‘List’:
List<Author> AuthorList = new ArrayList<Author>();
But the original doesn’t type to an interface, so the exact Java equivalent perhaps shouldn’t either.