Java Arraylist

This Comment will be submitted for moderation and will not be accessible to other users until it has been approved.


-3 points

What is the difference between Arraylist and Hashmap? What to use when?



4 points

ArrayList class provides methods for basic array operations.

The ArrayList class is a concrete implementation of List interface. This class supports dynamic arrays that can grow as needed. In java, standard arrays are of fixed length. After arrays are created, they cannot grow or shrink, which means you must know in advance how many elements an array will hold. However, sometimes you may not know how large an array you need. To handle this situation, collection framework has defined ArrayList class. An object of this can dynamically increase or decrease in size.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
 
public class Ex01 {
 
    public static void main(String[] args) throws IOException {
 
        BufferedReader userInput = new BufferedReader 
            (new InputStreamReader(System.in));
 
        ArrayList<String> myArr = new ArrayList<String>();
        myArr.add("abc");
        myArr.add("abcd");
        myArr.add("abcde");
 
        System.out.println("Dummy Text");
        System.out.println("Enter your name:");
        String name = userInput.readLine();
        Integer nameLength = name.length();
        if (nameLength == 0)
        {
            System.out.println("empty name entered");
            return;
        }
 
        Integer dummyIndex = nameLength % myArr.size();
 
        System.out.println("\nYour name is "+name+", its length is " + 
                        nameLength + " characters,\n" +
                        "that's why we suggest you to go to "
                        + myArr.get(dummyIndex ));
    }
}
 

Hashmap allows you to define your own indices. Map is an object that stores key/volume pairs. Given a key, you can find its value. Keys must be unique, but values may be duplicated. The HashMap class provides the primary implementation of the map interface. The HashMap class uses a hash table to implementation of the map interface. This allows the execution time of basic operations, such as get() and put() to be constant.

Anonymous's picture
Created by Anonymous

Post Comment

  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.