Core java interview Questions You'll Most Likely Be Asked (Second Edition)


Explain Bounded Generic Types with a code sample


Download 1.52 Mb.
Pdf ko'rish
bet56/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   52   53   54   55   56   57   58   59   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

Explain Bounded Generic Types with a code sample.
Answer:


Bounded Generic Types help to restrict the type that can be used
as a generic argument. The following code demonstrates this:
public class Shape {
}
public class Circle extends Shape{
}
public class ShapeDrawer {
public void drawShape(T shape) {
System.out.println(“Drawing Shape..”);
}
}
This code declares a superclass called Shape that has a sub–
class called Circle. It also specifies a class called
ShapeDrawer which is a generic type. Instead of directly
specifying T, the code specifies T extends Shape. This means
that the generic type T should be a sub–class of Shape. So, if the
drawShape method is invoked with an argument which is not a
sub–class of Shape, a compilation error will occur.



146.
147.
CHAPTER
14
Collections
What are the four main interfaces in the Java Collection
API.
Answer:
java.util.Collection is the top level interface in the Java
Collection API. It simply represents a group of values operated as
one unit. It has two main sub–interfaces Set and List. Both are
used to store a group of values; however, they differ slightly in the
way they store data.
A List allows duplicate elements i.e. the same element can be
present more than once. Also, a List is ordered i.e. elements in a
list are stored in the order in which they are inserted & this order
is maintained.
A Set does not allow duplicates & is unordered so the order in
which the elements are inserted into the Set will not be
maintained.
There is another top–level interface called Map. A Map is used to
store key–value pairs.

Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   52   53   54   55   56   57   58   59   ...   171




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling