JavaRush /Java Blog /Random EN /How to use the ArrayList, Vector and HashMap collection c...
ramhead
Level 13

How to use the ArrayList, Vector and HashMap collection classes provided by the Java Collections Framework

Published in the Random EN group
In this article, we will learn about three important collection classes ArrayList , Vector and HashMap from the Collections Framework and start using them in our own code. How to use the ArrayList, Vector and HashMap collection classes provided by the Java Collections Framework - 1Using the collection ArrayListand collection classes Vector, we can store a group of elements as simple objects and manipulate them using various methods available in these classes. Classes ArrayListand Vectorare available from the package java.util. Another class is a collection, available from the package java.util, this one HashMap, which allows you to store a collection of key-value mappings. This makes it possible to obtain the desired value from a collection when the key is known. Let's look at examples using these collection classes one by one. Example 1. In this example, we will write a simple program using a class - the ArrayList collection Listing 1. Execution code for example 1

// подключаем класс
import java.util.ArrayList;
public class ArrayListExample {
  static String[] favouriteCharacters = {"Harry", "Ron", "Hermione",  "Snape", "Dumbledore", "Moody", "Riddle", "Fred"};
   int i;
   public ArrayList favouritelist = new ArrayList();
// метод добавляет элементы ‘favouriteCharacters’ в ‘favouritelist’
 private void includeCharacters(String[]favouriteCharacters)
       {
        for (i = 0; i < favouriteCharacters.length; i++) {
            // добавление элементов по одному из массива ‘favouriteCharacters’
            favouritelist.add(favouriteCharacters[i]);
            printCharacters(i);
        }
// добавление элементов, посредством указания позиций
        favouritelist.add(1, "george");
        favouritelist.add(4, "Peter");
    }
// метод выводит элемент ‘favouritelist’ по указанной позиции
    private void printCharacters(int i) {
        System.out.println("Character " + (i + 1) + ":" + favouritelist.get(i));
    }
// метод выводит все элементы ‘favouritelist’
    private void printCharacters() {
        System.out.println("\n");
        for(int i=0;i<favouritelist.size();i++){
        System.out.println("Character" + (i + 1) + ":" + favouritelist.get(i));
    }    }
// метод возвращает размер коллекции ‘favouritelist’
    private int sizeofCharactersList() {
        System.out.println("\n");
        System.out.println("Total No of Characters in Array:" + favouriteCharacters.length);
        System.out.println("Total No of Characters in List:" + favouritelist.size());
        return favouritelist.size();
    }
// метод выводит позицию element ‘favouritelist’ по указанному имени
 public void getCharacterPostion(String characterName) {
     System.out.println("\n");
        System.out.println("The position of the character\t" + characterName + "\tis\t" + favouritelist.indexOf(characterName));
    }
// метод удаляет элемент ‘favouritelist’ по указанному имени
    public void removeCharacter(String characterName) {
        if(favouritelist.size()>favouriteCharacters.length){
        favouritelist.remove(characterName);
        }
        else{
             System.out.println("\n");
             System.out.println("The element\t"+favouritelist.get(favouritelist.indexOf(characterName))+"\tcannot be removed");
        }
        }
// метод удаляет элемент ‘favouritelist’ по указанной позиции
    public void removeCharacter(int i) {
        if(favouritelist.size()>favouriteCharacters.length){
        favouritelist.remove(i);
          }
        else{
            System.out.println("The element\t"+favouritelist.get(i)+"\tcannot be removed");
        }
    }
    public static void main(String args[]) {
        ArrayListExample example = new ArrayListExample();
        example.includeCharacters(favouriteCharacters);
        example.printCharacters();
        int size = example.sizeofCharactersList();
        example.getCharacterPostion("Ron");
        example.removeCharacter("Snape");
        example.removeCharacter(2);
        example.sizeofCharactersList();
        example.removeCharacter("Harry");
         example.removeCharacter(4);
    }
}
Running this program will produce the following output:

Character 1:Harry
Character 2:Ron
Character 3:Hermione
Character 4:Snape
Character 5:Dumbledore
Character 6:Moody
Character 7:Riddle
Character 8:Fred


Character1:Harry
Character2:george
Character3:Ron
Character4:Hermione
Character5:Peter
Character6:Snape
Character7:Dumbledore
Character8:Moody
Character9:Riddle
Character10:Fred


Total No of Characters in Array:8
Total No of Characters in List:10


The position of the character	Ron	is	2


Total No of Characters in Array:8
Total No of Characters in List:8


The element	Harry	cannot be removed
The element	Dumbledore	cannot be removed
Let's look at the example program provided, step by step. In this example, in the very first line of the program, we import the class - collection ArrayList. Then, we take turns initializing an array of strings favouriteCharacterscontaining the names of people and favouritelistan instance of the collection ArrayList. The method includeCharacters(args)can be divided into two parts. In the first part of the method, elements are added from the array to the collection using a loop. In this case, adding elements to ArrayListis done in the same order in which they are located in the array. This happens because we do not define any positions for the elements that are added to the collection. But in the second part of our method, elements are added using indexing. In this case, elements are added to the collection at the exact position specified. When a new element is added to the middle of a collection ArrayList, elements already existing in that collection that are located beyond the specified insertion position of the new element are shifted to subsequent positions from their own, thus increasing the size of the collection. When we look at the output first, we will see:

Total No of Characters in List: 10
Total No of Characters in Array: 8
This is because in addition to the array having 8 elements, which are added to ArrayList, we explicitly add 2 more elements, thus increasing the size of the collection to 10. The method getCharacterPosition(args)takes the value of an element (person's name) and displays the position of this element in the collection ArrayList. If there is no such element in ArrayList, then the value -1 is displayed. The method removeCharacter(args)removes the specified element value (person's name) from the collection, taking as an argument either the index of that element or the element itself. In the above code, we can notice that the size of our collection has become 8 instead of 10 due to the fact that we have removed 2 elements from the collection. If the sizes of the array and collection are the same, then the method returns the following lines:

The element Harry cannot be removed 
The element Dumbledore cannot be removed
The execution of the method removeCharacter(args)is only conditioned by the fact that the size of the collection must be greater than the size of the array. Example 2. In this example, we will write a simple program using a class - a collection Vector Listing 2. Execution code for example 2

// подключаем класс
import java.util.Vector;
public class VectorExample {
    Vector vector=new Vector();
    public void addCharacterandPrint(){
        vector.add("Weasley");
        vector.add("Potter");
        for(int i=0;i<vector.size();i++){
        System.out.println("The characters are\t"+vector.get(i));
        }
    }
    public static void main(String args[]){
        VectorExample example=new VectorExample();
        example.addCharacterandPrint();
        }
}
Running this program will produce the following output:

The characters are Weasley
The characters are Potter
The above code is just a small sample, provided as proof that there is not much difference between collections ArrayListand Vector. The collection Vectorcan be manipulated in the same way as the collection ArrayList, using the same methods. Example 3. In this example, we will write a simple program using the collection class HashMap Listing 3. Execution code for Example 3

// подключаем класс
import java.util.HashMap;
public class HashMapExample {
    HashMap hashMap=new HashMap();
    String Books[]={"Famous Five","Goosebumps","Robinson Crusueo","Nancy Drew","The Cell","The Davinci Code","Harry Potter"};
    public void mapAuthors(){
        hashMap.put("Famous Five","Enid Blyton");
        hashMap.put("Goosebumps","R.L.Stine");
        hashMap.put("Nancy Drew","Carolyn Keene");
        hashMap.put("The Cell","Christopher Pike");
        hashMap.put("The Davinci Code","Dan Brown");
        hashMap.put("Harry Potter","J.K. Rowling");
    }
    public void getBookList(){
        for(int i=0;i<Books.length;i++){
            if(hashMap.containsKey(Books[i])){
                System.out.println("Author"+(i+1)+":\t"+hashMap.get(Books[i])+"\t"+Books[i]);
            }
            else{
                System.out.println("\nThe Imformation about the author of the book\t"+Books[i]+"\tis not available\n");
            }
        }
    }
    public static void main(String args[]){
        HashMapExample hashMapExample=new HashMapExample();
        hashMapExample.mapAuthors();
        hashMapExample.getBookList();
    }
}
Running this program will produce the following output:

Author1: Enid Blyton Famous Five
Author2: R.L.Stine Goosebumps
The Information about the author of the book Robinson Crusueo is not available
Author4: Carolyn Keene Nancy Drew
Author5: Christopher Pike The Cell
Author6: Dan Brown The Davinci Code
Author7: J.K. Rowling Harry Potter
Let's look at the code above, step by step. In this example program, we have an array of strings whose elements are the names of famous books. The method mapAuthors()creates a display of book titles with their authors. The keys here are the titles of the books, and the values ​​are the authors of those books. When the method is called getBookList(), it iterates through the array Booksand gets the book titles one by one. Next, the method checks whether any book has its own author. As we can see, if the method cannot find the author of the book, then the message is displayed not available. Otherwise, the author and his book are displayed one by one. Conclusion: In this article, we studied a little about the classes - collections ArrayList, Vector, HashMapand tried to use them in our own code. Original article: How to use ArrayList, Vector and HashMap classes provided by Java Collections Framework
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION