Day14 yourself define the use of generic classes

Source: Internet
Author: User

Introduction and embodiment of generics:

Problem: The collection can store various types of elements, but because the collection can store various types of data. When you get an element in a collection, it makes the data unsafe.

public class Genericdemo {public static void main (String []str) {List List = new ArrayList (); List.add (10);//self-actively boxed List.add (new Integer); List.add (integer.valueof ()); for (Object obj:list) System.out.println (obj);}}

In development, a situation can occur where a user enters a data and stores it in a collection. However, the user may enter a string type of data


public static void Main (String []str) {List List = new ArrayList (); List.add ("ten"); List.add (new Integer); List.add ( Integer.valueof (+)); for (Object obj:list) {integer num = (integer) obj; SYSTEM.OUT.PRINTLN (num);}}

Exception in thread "main" java.lang.ClassCastException:java.lang.String cannot is cast to Java.lang.Integer
At Cn.itcast.test.GenericDemo.main (genericdemo.java:17)

Workaround: Ability to use Instanceofkeyword to avoid classcastexception exceptions

After the JDK1.5. A new approach has emerged: generics


Think: Assuming that the collection can only store one type of element, will there be an issue with getting data unsafe?

Implementation method: when you define a collection, you understand the types of elements that can be stored in the collection


Usage format for generics: < reference type > Note: Only reference types can be used in generics


Package Org.test;import Java.util.arraylist;import Java.util.list;public class Testgeneric {public static void main ( String[] (args) {//define the use of a generic class by itself//1. Specifies the generic type when instantiating an object of a generic class, which cannot be a generic type, only where the reference type//all uses the generic type. To become the type of the generic class//2. Assuming that the type is not specified, the default is the object type order<integer> o = new order<integer> ();//order oo = New Order ();// Assuming that the type of the generic is not specified, the default is the object type list<integer>list = O.getlist (); List.add (); List.add (11); System.out.println (O.getlist ()); Integer i = o.gete (100); System.out.println (i);}} Class Order<t>{int MaxSize = 30;//public T []t = new T[maxsize];   No generic array private T t;private list<t> list = new arraylist<t> ();p ublic list<t> getList () {return List;} Declare a generic method  <E> Be sure to follow the permission modifier. Cannot lack public <E> e Gete (e e) {return e;}} Subclass or indeterminate type T, when instantiating an object of a subclass to indicate a generic reference type//inherited generic class or generic interface, it is possible to indicate the generic type class Suborder<integer> extends Order<integer >class Suborder <t>extends order<t>{}

What are the benefits of generics?

1, overcomes the security of storing data in the collection

2, the execution of the exception can occur at compile time as a compilation error processing, to avoid the execution of the exception

3. Writing that enforces type conversions in code is omitted

@Testpublic void Demo2 () {list<integer> List = new arraylist<integer> (); List.add () List.add (New Integer ( ); List.add (integer.valueof (1000));//Iterate through the collection using iterators. In the iterator, understand the type for iteration (iterator<integer> it = List.iterator (); It.hasnext ();) {//Because the iterator understands the type to iterate. So there is no need to force type conversion//integer num = (Integer) it.next ();//Do not need to force type conversion to Integer num = It.next (); SYSTEM.OUT.PRINTLN (num);} Use foreach to iterate through the collection//Because the list collection is aware of the type of the collection, it is possible to declare directly as an element type in the collection in foreach, instead of the previous objectfor (Integer i:list) { System.out.println (i);}}


Day14 yourself define the use of generic classes

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.