Effective Java


// Typesafe heterogeneous container pattern - API



Download 2,19 Mb.
Pdf ko'rish
bet141/341
Sana11.07.2022
Hajmi2,19 Mb.
#776765
1   ...   137   138   139   140   141   142   143   144   ...   341
Bog'liq
Effective Java

// Typesafe heterogeneous container pattern - API
public class Favorites {
public  void putFavorite(Class type, T instance);
public  T getFavorite(Class type);
}
Here is a sample program that exercises the 
Favorites
class, storing, retriev-
ing, and printing a favorite 
String

Integer
, and 
Class
instance:
// Typesafe heterogeneous container pattern - client
public static void main(String[] args) {
Favorites f = new Favorites();
f.putFavorite(String.class, "Java");
f.putFavorite(Integer.class, 0xcafebabe);
f.putFavorite(Class.class, Favorites.class);


CHAPTER 5
GENERICS
152
String favoriteString = f.getFavorite(String.class);
int favoriteInteger = f.getFavorite(Integer.class);
Class favoriteClass = f.getFavorite(Class.class);
System.out.printf("%s %x %s%n", favoriteString,
favoriteInteger, favoriteClass.getName());
}
As you would expect, this program prints 
Java cafebabe Favorites
. Note, inci-
dentally, that Java’s 
printf
method differs from C’s in that you should use 
%n
where you’d use 
\n
in C. The 
%n
generates the applicable platform-specific line
separator, which is 
\n
on many but not all platforms.

Favorites
instance is 
typesafe
: it will never return an 
Integer
when you
ask it for a 
String
. It is also 
heterogeneous
: unlike an ordinary map, all the keys
are of different types. Therefore, we call 
Favorites

typesafe heterogeneous
container
.
The implementation of 
Favorites
is surprisingly tiny. Here it is, in its entirety:

Download 2,19 Mb.

Do'stlaringiz bilan baham:
1   ...   137   138   139   140   141   142   143   144   ...   341




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

kiriting | ro'yxatdan o'tish
    Bosh sahifa
юртда тантана
Боғда битган
Бугун юртда
Эшитганлар жилманглар
Эшитмадим деманглар
битган бодомлар
Yangiariq tumani
qitish marakazi
Raqamli texnologiyalar
ilishida muhokamadan
tasdiqqa tavsiya
tavsiya etilgan
iqtisodiyot kafedrasi
steiermarkischen landesregierung
asarlaringizni yuboring
o'zingizning asarlaringizni
Iltimos faqat
faqat o'zingizning
steierm rkischen
landesregierung fachabteilung
rkischen landesregierung
hamshira loyihasi
loyihasi mavsum
faolyatining oqibatlari
asosiy adabiyotlar
fakulteti ahborot
ahborot havfsizligi
havfsizligi kafedrasi
fanidan bo’yicha
fakulteti iqtisodiyot
boshqaruv fakulteti
chiqarishda boshqaruv
ishlab chiqarishda
iqtisodiyot fakultet
multiservis tarmoqlari
fanidan asosiy
Uzbek fanidan
mavzulari potok
asosidagi multiservis
'aliyyil a'ziym
billahil 'aliyyil
illaa billahil
quvvata illaa
falah' deganida
Kompyuter savodxonligi
bo’yicha mustaqil
'alal falah'
Hayya 'alal
'alas soloh
Hayya 'alas
mavsum boyicha


yuklab olish