Comments (2)
Da, kao što piše u komentarima ispod.
Neka imamo npr. Point p = new Point<>(...)
Interno, zbog načina kako Java implementira Generics, private T x se pretvara u private Object x, pa je i getX() referenca tipa Object (a objekt na kojeg ta referena pokazuje bit će konkretnog tipa po kojem je izvršena parametrizacija), ali zato kompajler doda downcast u (String) getX()
pa je tako
String s = p.getX();
zapravo
String s = (String) p.getX();
Na taj način nam kompajler daje tipsku sigurnost kod rada s genericsima usprkos tome što u Javinoj virutalnoj mašini genericsi kao takvi ne postoje.
Razlog zašto možemo napisati Object o = p.getX()
je zato što za svaku referencu možemo napraviti upcast u Object. Kad imamo referencu tipa Object, kompajler će nas pustiti da napravimo downcast u bilo što, ali onda postoji šansa da prilikom izvršavanja programa utvrdi da downcast nije bio ispravan i baci ClassCastException.
Tako nam je programski kod
Integer i = (Integer)(Object)sPoint.getX();
zapravo
Integer i = (Integer)(Object)(String) sPoint.getX();
i puknut će prilikom izvršavanja, jer downcast iz Object u Integer nije moguć, jer objekt u stvarnosti nije Integer, već je bio String.
// But you can force compiler to forget types:
Integer i = (Integer)(Object)sPoint.getX();
// so now the following line will compile, but
// will never execute since the previous one will
// throw an exception...
System.out.println(i.intValue());
from lectures.
U redu hvala
from lectures.
Related Issues (1)
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from lectures.