settingsAccountsettings
Menusettings

Q: How to create a List in Java?

+14 votes

Hi. Can you give me some examples of how can I create a list in Java and some of it's methods (adding/removing elements to it)?

Thanks

asked in Java category by user Jolie Ann

2 Answers

+2 votes
 
Best answer

First you can read about Java collections here: https://docs.oracle.com/javase/8/docs/technotes/guides/collections/overview.html

Interface Hash Table Resizable Array Balanced Tree Linked List Hash Table + Linked List
Set HashSet   TreeSet   LinkedHashSet
List   ArrayList   LinkedList  
Deque   ArrayDeque   LinkedList  
Map HashMap   TreeMap   LinkedHashMap

Classes that implement the collection interfaces typically have names in the form of <Implementation-style><Interface>.

In my code you will find some good examples of the usage of Lists in Java:

import java.util.ArrayList;
import java.util.List;

public class ArrayListCode {
    public static void main(String[] args) {
        List<String> listOne = new ArrayList<>();//ArrayLists are like resizable arrays
        listOne.add("USA");
        listOne.add("United Kingdom");
        listOne.add("France");
        listOne.add("Italy");

        System.out.println(listOne);

        listOne.add("Bulgaria");
        System.out.println(listOne);

        listOne.remove(0);//WHICH ELEMENT IN THE LIST TO REMOVE - IN THIS CASE IT WILL BE "USA"
        System.out.println(listOne);

        String country = listOne.get(1);//WHICH ELEMENT TO GET FROM THE LIST
        System.out.println("The second country is: " + country);

        int pos = listOne.indexOf("Italy");//WHICH IS THE POSITION OF "Italy"
        System.out.println("The position of Italy in the ArrayList is: " + pos);
    }
}
  • On line 14: you can see how to add an element to the list using the method .add()
  • On line 17: you can see how to remove a particular element from certain position in the list by using the method .remove()
  • On line 20: you can see how to show particular element from a certain position in the list with the method .get()
  • On line 23: you can see how to show a particular position of a certain element in the list with the method .indexOf()

Also, this page will explain more about the lists in Java: http://docs.oracle.com/javase/8/docs/api/java/util/List.html

The output:

[USA, United Kingdom, France, Italy]
[USA, United Kingdom, France, Italy, Bulgaria]
[United Kingdom, France, Italy, Bulgaria]
The second country is: France
The position of Italy in the ArrayList is: 2

answered by user andrew
edited by user golearnweb
+2 votes

To understand better the collections in Java, watch these tutorials:

Here is the link to the playlist with all the videos about the various collections in Java with nice visual explanations (13 videos): https://www.youtube.com/playlist?list=PLB841C370FAFB8EC7

answered by user ak47seo
edited by user golearnweb
...