概念:泛型,即“參數(shù)化類型”。就是將原來(lái)具體的類型參數(shù)化,類似于方法中的變量參數(shù),此時(shí)類型也定義成參數(shù)形式(可以稱之為類型形參),然后在使用/調(diào)用時(shí)傳入具體的類型(類型實(shí)參)。
本質(zhì):為了參數(shù)化類型(在不創(chuàng)建新的類型的情況下,通過(guò)泛型指定的不同類型來(lái)控制形參具體限制的類型)。也就是說(shuō)在泛型使用過(guò)程中,操作的數(shù)據(jù)類型被指定為一個(gè)參數(shù),這種參數(shù)類型可以用在類、接口和方法中,分別被稱為泛型類、泛型接口、泛型方法。
三種使用方式:泛型類、泛型接口、泛型方法
類型通配符:
1)類型通配符一般是使用?代替具體的類型參數(shù)。例如List> 在邏輯上是List
2)類型通配符上線通過(guò)形如List來(lái)定義,如此定義就是通配符泛型值接受Number及其下層子類類型。
泛型提供了編譯時(shí)類型安全監(jiān)測(cè)機(jī)制,該機(jī)制允許程序員在編譯時(shí)檢測(cè)到非法的類型。泛型的本質(zhì)是參數(shù)化類型,也就是說(shuō)所操作的數(shù)據(jù)類型被指定為一個(gè)參數(shù)。比如我們要寫(xiě)一個(gè)排序方法,能夠?qū)φ麛?shù)數(shù)組、字符串?dāng)?shù)組甚至其他任何類型的數(shù)組進(jìn)行排序,我們就可以使用Java泛型。
1.泛型方法
你可以寫(xiě)一個(gè)泛型方法,該方法在調(diào)用時(shí)可以接收不同類型的參數(shù)。根據(jù)傳遞給泛型方法的參數(shù)類型,編譯器適當(dāng)?shù)靥幚砻恳粋€(gè)方法調(diào)用。
//?泛型方法?printArray? ?????public?static?< E >?void?printArray(?E[]?inputArray?) ?????{? ?????????for?(?E?element?:?inputArray?){? ?????????????System.out.printf(?"%s?",?element?); ?????????} ?????}
1)<?extend T> 表示該通配符所代表的類型是T類型的子類。
2) super T> 表示該通配符所代表的類型是T類型的父類。
2.泛型類
泛型類的聲明和非泛型類的聲明類似,除了在類名后面添加類型參數(shù)聲明部分。和泛型方法一樣,泛型類的類型參數(shù)聲明部分也包含一個(gè)或多個(gè)類型參數(shù),參數(shù)間用逗號(hào)隔開(kāi)。一個(gè)泛型參數(shù),也被稱為一個(gè)類型變量,是用于指定一個(gè)泛型類型名稱的標(biāo)識(shí)符。因?yàn)樗鼈兘邮芤粋€(gè)或多個(gè)參數(shù),這些類被稱為參數(shù)化的類或參數(shù)化的類型。
public?class?Box<T>?{ ?????private?T?t; ?????public?void?add(T?t)?{ ?????????this.t?=?t; ?????} ?????public?T?get()?{ ?????????return?t; ?}
3.類型擦除
Java中的泛型基本上都是在編譯器這個(gè)層次來(lái)實(shí)現(xiàn)的。在生成的Java字節(jié)碼中是不包含泛型中的類型信息的。使用泛型時(shí)加上的類型參數(shù),會(huì)被編譯器在編譯時(shí)去掉,這個(gè)過(guò)程就稱為類型擦除。如在代碼中定義的List
本文來(lái)自?java入門?欄目,歡迎學(xué)習(xí)!
The above is the detailed content of Learn more about Java generics. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

ChromecanopenlocalfileslikeHTMLandPDFsbyusing"Openfile"ordraggingthemintothebrowser;ensuretheaddressstartswithfile:///;2.SecurityrestrictionsblockAJAX,localStorage,andcross-folderaccessonfile://;usealocalserverlikepython-mhttp.server8000tor

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,
