Java 1.5 Tiger A Developers Notebook [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Java 1.5 Tiger A Developers Notebook [Electronic resources] - نسخه متنی

David Flanagan, Brett McLaughlin

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید








5.4 Specify Object Arguments Over Primitives


As discussed in Chapter 4, Tiger adds a variety of new features through
unboxing. This allows you, in the case of varargs, to use object wrapper types in your method arguments.


5.4.1 How do I do that?


Remember that every class in Java ultimately is a descendant of java.lang.Object. This means that any object can be converted to an Object;
further, because primitives like int and short are now automatically
converted to their object wrapper types (Integer and Short in this case),
any Java type can be converted to an Object.

Thus, if you want to accept the widest variety of argument types in your
vararg methods, use an object type as the argument type. Better yet, go
with Object for the absolute most in versatility. For example, take a
method that did some printing:


private String print(Object... values) {
StringBuilder sb = new StringBuilder( );
for (Object o : values) {
sb.append(o)
.append(" ");
}
return sb.toString( );
}

The basic idea here is to print anything and everything. However, the
more obvious way to declare this method is like this:

  
private String print(String... values) {
StringBuilder sb = new StringBuilder( );
for (Object o : values) {
sb.append(o)
.append(" ");
}
return sb.toString( );
}

The problem here is that now this method won't take Strings, ints, floats, arrays, and a variety of other types, all of which you might want to legitimately print.

By using a more general type, Object, you obtain the ability to print anything and everything.


/ 131