JavaRush /Java Blog /Random EN /How to use classes - ArrayList, Vector and HashMap collec...
ramhead
Level 13

How to use classes - ArrayList, Vector and HashMap collections provided by Java Collections Framework

Published in the Random EN group
In this article, we will learn about three important classes - the ArrayList , Vector and HashMap collections from the Collections Framework and start using them in our own code. How to use classes - ArrayList, Vector and HashMap collections provided by Java Collections Framework - 1Using the collection ArrayListand collection classes Vector, we can store a group of elements as simple objects and manipulate them through the various methods available in these classes. Classes ArrayListand Vectorare available from the java.util. Another class is a collection available from the package java.util, this isHashMap, which allows you to store a collection of mappings: key - value. This makes it possible to get the desired value from the collection when the key is known. Let's look at examples using these classes - collections in turn. Example 1. In this example, we will write a simple program using the ArrayList collection class Listing 1. Example 1 execution code
// подключаем класс
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 take a look at an example of the above program, step by step. In this example, on the very first line of the program, we are importing a class, a collection of ArrayList. Then, in turn, we initialize an array of strings favouriteCharacterscontaining the names of people and favouritelist- an instance of the collection ArrayList. The method includeCharacters(args)can be conditionally 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 toArrayListare processed in the same order as they appear in the array. This is because we don't 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 exactly the specified position. When a new element is added to the middle of a collection ArrayList, the elements already existing in that collection and located after the specified insertion position of the new element are shifted to the next 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 that has 8 elements that 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 the 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 either the index of this element or the element itself as an argument. In the above code, we can notice that our collection size is now 8 instead of 10 because we removed 2 items from the collection. If the array and collection sizes are the same, then the method returns the following strings:
The element Harry cannot be removed
The element Dumbledore cannot be removed
The execution of the method removeCharacter(args)is due only to 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 collection class Vector Listing 2. Example 2 execution code
// подключаем класс
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 ArrayListusing the same methods. Listing 3. In this example, we will write a simple program using a collection class HashMap Listing 3. Example 3 execution code
// подключаем класс
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 break down the code of the above program, step by step. In this example program, we have an array of strings whose elements are the titles 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 in turn. Next, the method checks if 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 after the other. Conclusion: In this article, we studied a little classes - collections ArrayList, Vector,HashMapand tried to use them in your 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