Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

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

In this article, we will learn about three important classes ArrayList, Vector and HashMap from Collections Framework and start using these classes in our code.

Using ArrayList and Vector classes we can treat a group of elements as a single object and manipulate it with the help of various methods that are available in these classes. ArrayList and Vector classes are available in java.util package.

HashMap is another class, available in java.util package, which maps key and value. It helps us retrieve the value when key is known. Let us look at these classes and its usage one by one.

Step 1: In this Step we will write a simple program which uses ArrayList.

Listing 1: Below is the code to execute Step 1

// import statements
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();
   // method to add ‘favouriteCharacters’  to the ‘favouritelist’
 private void includeCharacters(String[]favouriteCharacters)
       {
        for (i = 0; i < favouriteCharacters.length; i++) {
            // Adding elements one by one from the array
            favouritelist.add(favouriteCharacters[i]);
            printCharacters(i);
        }
// Adding elements again, by specifying the exact position
        favouritelist.add(1, "george");
        favouritelist.add(4, "Peter");
    }
// method to print ‘favouriteCharacters’ one by one
    private void printCharacters(int i) {
        System.out.println("Character " + (i + 1) + ":" + favouritelist.get(i));
    }
// method to print ‘favouriteCharacters’ one by one
    private void printCharacters() {
        System.out.println("\n");
        for(int i=0;i<favouritelist.size();i++){
        System.out.println("Character" + (i + 1) + ":" + favouritelist.get(i));
    }    }
// method to get size of ‘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();
    }
// method to get the postion of the ‘favouriteCharacters’
 public void getCharacterPostion(String characterName) {
     System.out.println("\n");
        System.out.println("The position of the character\t" + characterName + "\tis\t" + favouritelist.indexOf(characterName));
    }
// method  to remove  ‘favouriteCharacters’ by name
    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");
        }
        }
// method  to remove  ‘favouriteCharacters’ by index value
    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 give us the following output:

Output of listing 1

Figure 1: Output of listing 1

Let us analyze the above program step by step:

In the above program, we are importing ArrayList class, which is the first line of the program.

Then we are initializing, an array of string which contains some names and an arraylist of generic type.

The method ‘includeCharacters(args) ‘ can be divided in to two sections.

In the first scenario the elements are added from the array to the list, by means of a loop. In this case, the elements are added to the ArrayList in the same order as it is in the array. This is because we are not defining any position for the element that is to be added in the list.

But in the second scenario, the elements are added with an index specification. In this case the element is added to the arraylist at the specified index. When a new element is added to the ArrayList, the elements which were already in the ArrayList gets pushed down to the next index, from their respective positions, thus increasing the size of the ArrayList.

When we look at the output, the first time it shows:

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

Because the array has 8 elements, which is added to the ArrayList, and then we are explicitly adding 2 more elements, thus making the size of ArrayList 10.

The method ‘getCharacterPostion(args) ‘ accept a string and displays the position of the string in the ArrayList. If the string is not at all available in the ArrayList then the output will be ‘-1’.

The method ‘removeCharacter(args)’ removes the specified string from the arraylist, by accepting index value of the string (or) by accepting the string itself. In the above code, we can see the size of the ArrayList becomes 8 from 10 because 2 elements got removed from the ArrayList. If the size of the string array and the size of the ArrayList is same, the removeCharacter(args) method prints

The element Harry cannot be removed
The element Dumbledore cannot be removed

Because the removeCharacter(args) is conditioned to execute only if the size of the arraylist is greater than the size of the string array.

Step 2: In this Step we will write a simple program using Vector class.

Listing 2: Below is the code to execute Step 2

// import statements
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 give us the following output:

The characters are Weasley
The characters are Potter

The above code is just a sample to prove that there is not much difference between an ArrayList and a Vector. A Vector can be manipulated like an ArrayList with the same methods.

Step 3: In this Step we will write a simple program using HashMap class.

Listing 3: Below is the code to execute Step 3

//import statements
import java.util.HashMap;
import java.util.Set;
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 give us 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 us analyze the above program step by step:

In the above code, we have a string array with some book names. The method ‘mapAuthors()’ maps the book names with its authors. Here, book names act as key and author names act as values. When ‘getBookList()’ method gets executed it iterates the ‘Books’ array and gets the book names one by one. The method checks whether the book name has got any author. As we can see if the method could not find an author for a book, it prints a ‘not available’ message. Else it prints the required output one by one.

Conclusion:

In this article, we have learnt about Arraylist, Vector and HashMap classes and also used them in our own code.



Have done the bachelor's in computer's and have done various courses on many front-end and back-end languages as Java, HTML, CSS, Javascript.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login