How do I create type specific collections?

Category: fundamental, viewed: 4477 time(s).
package org.kodejava.example.intro;

import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;

public class TypeSpecificCollection {
    public static void main(String[] args) {
        //
        // Using a Generic can enable us to create a type specific collection
        // object. In the example below we create a Map whose key is an Integer
        // a have the value of a String.
        //
        Map<Integer, String> grades = new HashMap<Integer, String>();

        grades.put(1, "A");
        grades.put(2, "B");
        grades.put(3, "C");
        grades.put(4, "D");
        grades.put(5, "E");

        //
        // A value obtained from type specific collection doesn't not need to
        // be casted, it knows the type returned.
        //
        String value = grades.get(1);

        //
        // Creating a List that will contains a String only values.
        //
        List<String> dayNames = new ArrayList<String>();
        dayNames.add("Sunday");
        dayNames.add("Monday");
        dayNames.add("Tuesday");
        dayNames.add("Wednesday");

        //
        // We also don't need to cast the retrieved value because it knows the
        // returned type object.
        //
        String firstDay = dayNames.get(0);
    }
}
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Uncensored Newsgroups
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Java Training

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats