为什么java System.out.print方法有各种形式?
为什么java System.out.print方法有各种形式?,java,Java,我打开了java.io.PrintStream类文件。我发现有各种各样的打印方法。每个方法99%相同,但仅不包含参数类型。许多编程指南都建议在这种情况下可以使用泛型(或模板)。所以我想知道为什么java.io.Printstream不使用generic。如果您使用 public void print(long l) { write(String.valueOf(l)); } /** * Prints a floating-point number. The string produ
我打开了java.io.PrintStream类文件。我发现有各种各样的打印方法。每个方法99%相同,但仅不包含参数类型。许多编程指南都建议在这种情况下可以使用泛型(或模板)。所以我想知道为什么java.io.Printstream不使用generic。如果您使用
public void print(long l) {
write(String.valueOf(l));
}
/**
* Prints a floating-point number. The string produced by <code>{@link
* java.lang.String#valueOf(float)}</code> is translated into bytes
* according to the platform's default character encoding, and these bytes
* are written in exactly the manner of the
* <code>{@link #write(int)}</code> method.
*
* @param f The <code>float</code> to be printed
* @see java.lang.Float#toString(float)
*/
public void print(float f) {
write(String.valueOf(f));
}
/**
* Prints a double-precision floating-point number. The string produced by
* <code>{@link java.lang.String#valueOf(double)}</code> is translated into
* bytes according to the platform's default character encoding, and these
* bytes are written in exactly the manner of the <code>{@link
* #write(int)}</code> method.
*
* @param d The <code>double</code> to be printed
* @see java.lang.Double#toString(double)
*/
public void print(double d) {
write(String.valueOf(d));
}
/**
* Prints an array of characters. The characters are converted into bytes
* according to the platform's default character encoding, and these bytes
* are written in exactly the manner of the
* <code>{@link #write(int)}</code> method.
*
* @param s The array of chars to be printed
*
* @throws NullPointerException If <code>s</code> is <code>null</code>
*/
public void print(char s[]) {
write(s);
}
因此,int
值将被装箱,这意味着性能损失和不必要的内存使用
这就是您经常会发现所有primitiv数据类型的方法重载的原因
同样正如Taschi指出的,该类在Java中比泛型更古老。基元类型不是对象,因此不能用作泛型类型。另外,对于特定类型,某些方法确实具有特定的行为。这些方法也早于Java中泛型的存在,Java 1.0中甚至不存在自动装箱/拆箱和泛型。
public <T> void print(T value);
public void print(Integer value);