Java DAY14 Generics

Source: Internet
Author: User

Why use generics

1. Addressing security issues with element storage

2. Solve the problem of type conversion when getting elements


Generics not used

Package org.tizen.test;


Import java.util.ArrayList;
Import java.util.List;

public class Testmain {
public static void Main (String []str)
{
List List = new ArrayList ();
List.add (13);

List.add (14);

Any object and its subclasses that are not using generics can be added to the list

list.add ("Test");
for (int i = 0; I<list.size (); i++)

{

Exception in thread "main" java.lang.ClassCastException:java.lang.String cannot is cast to//java.lang.integer

int a = (Integer) list.get (i);
System.out.println (a);
}


}

}

Using generics

list<integer> List = new arraylist<integer> ();
List.add (30);
List.add (100);
List.add ("AA");
for (int i = 0; I<list.size (); i++)
{
int a = List.get (i);
System.out.println (a);
}



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java DAY14 Generics

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.