








Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An in-depth exploration of java generics, focusing on the concepts of bounded and unbounded wildcards, raw types, and ensure and restrictions. It covers the importance of wildcards, the differences between bounded and unbounded wildcards, the use of lower and upper bounds, and the advantages of using generic types instead of raw types. The document also explains the concept of type erasure and compile-time checking, as well as the restrictions on generics such as creating instances of generic types, generic array creation, and using generic types in static contexts.
Typology: Slides
1 / 14
This page cannot be seen from the preview
Don't miss anything!









public^ static
void^ main(String[]
args^ )^ {
p^
(^ g[]^ g
) { Rectangle^ rectangle
=^ new^ Rectangle(2,
2);
Circle9^ circle
=^ new^ Circle9(2); System out println("Same area? " + equalArea(rectangle
circle));
System.out.println( Same
area?^ +^ equalArea(rectangle
,^ circle));
} bli^ t ti^
E^ t^ d^ G^
t i Obj^ t^ b
l
public^ static
boolean equalArea(E^ object1,
E^ object2)^ { return^ object1.getArea()
==^ object2.getArea(); }
This^ is^ roughly
equivalent^
to ArrayList
list^ =^ new
ArrayList();
//^ Max1.java:
Find^ a^ maximum
object
Max1^ { /**^ Return
the^ maximum
between^ two
objects^ */
public^ static
>
E
p^
p max(E^ o1,^
E^ o2)^ { if^ (o1.compareTo(o2)
>^ 0) return^ o1;elsereturn o2;return^ o2; } } Max.max("Welcome", 23);
18
}
are^ necessary?
See^ this^ example.
WildCardDemo2WildCardDemo
WildCardDemo3WildCardDemo
TestArrayListNewTestArrayListNew
RunRun
22 docsity.com
stack1^ =^ new
GenericStack();
GenericStack
stack2^ =^ new
GenericStack();GenericStack();
Although^ GenericStack and
GenericStack b^ h^ i l^
l^ G^ i S
k
are^ two^ types,
but^ there^ i
s^ only^ one^
class^ GenericStack
loaded^ into
the^ JVM.
^ Restriction
1:^ Cannot^
Create^ an^ Instance
of^ a^ Generic
Type (i e^
new E())
Type.^ (i.e.,^
new^ E()). ^ Restriction 2: Generic Array Creation is Not Allowed^ Restriction
2:^ Generic
Array^ Creation
is^ Not^ Allowed
(i.e.,^ new^ E[100]). Restriction
3:^ A^ Generic
Type^ Parameter
of^ a^ Class^ Is
Not^ Allowed
in^ a^ Static^
Context. ^ Restriction
4:^ Exception
Classes^ Cannot
be^ Generic.^25
IntegerMatrix
E, element2: E): E
RationalMatrix^27
gives^ two^ programs
that
class^ for^ integer
matrix
arithmetic^
and^ rational
matrix^ arithmetic. TestIntegerMatrixTestIntegerMatrix^
RunRun
IntegerMatrixIntegerMatrix
TestRationalMatrixTestRationalMatrix
RunRun
RationalMatrixRationalMatrix