在Java中,数组不会覆盖toString(),因此如果您尝试直接打印数组,则会获得className + @ + className数组的十六进制,如下所示hashCode:
int[] intArray = new int[] {1, 2, 3, 4, 5};
System.out.println(intArray); // prints something like '[I@3343c8b3'
Run Code Online (Sandbox Code Playgroud)
但通常我们实际上想要更像的东西Object.toString().这样做最简单的方法是什么?以下是一些示例输入和输出:
// Array of primitives:
int[] intArray = new int[] {1, 2, 3, 4, 5};
//output: [1, 2, 3, 4, 5]
// Array of object references:
String[] strArray = new String[] {"John", "Mary", "Bob"};
//output: [John, Mary, Bob]
Run Code Online (Sandbox Code Playgroud) 这是java包树:http: //docs.oracle.com/javase/7/docs/api/java/lang/package-tree.html
我读了一篇关于Java的教程,该教程表明在Java数组中是对象.
数组类在哪里?为什么我们可以制作这样的数组:
byte[] byteArr = new byte[];
char[] charArr = new char[];
int[] intArr = new int[];
Run Code Online (Sandbox Code Playgroud)
并且数组将从Object继承方法; 例如:
byte thisByte = 1;
byte thatByte = 2;
byte[] theseBytes = new byte[] {thisByte, thatByte};
int inheritance = theseBytes.length; //inherited 'length' field and some methods
int wasntInWill = thatByte.length; //error
Run Code Online (Sandbox Code Playgroud)
这里发生了什么?
编辑:
根据答案,我现在知道它是一个包装final类java.lang.reflect.
我现在已经java.lang.reflect在我的Android项目中创建了一个包,并为其添加了一个名为Array.java的类.为了确认这是原始类的方式,Eclipse给了我错误"...已存在于path/to/android.jar"
如果我写出同一个类,java.lang.reflect.Array但改变toString()方法......这应该在我的应用程序中正常工作吗?
我有一个字符串数组,其中包含我定义的四个元素.我怎么打字System.out.println(name of Array),它不输出元素?但反而给了我一个奇怪的输出.
这是我的代码......
public class GeniusTrial {
public static void main(String[]args) {
String [] genius = {"Einstein, ", "Newton, ", "Copernicus, ", "Kepler."};
System.out.print(genius);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我得到的输出:
[Ljava.lang.String;@3e25a5
Run Code Online (Sandbox Code Playgroud) 以下是我刚刚编写的一个人为例子,以帮助我理解java的内部工作原理.
public class Main {
public static void main(String[] args) {
int[] a;
a = new int[12];
System.out.println(a);
}
}
Run Code Online (Sandbox Code Playgroud)
这打印出一些垃圾.由于a是通过引用传递的,我假设println获取a的内存地址,并将其作为字符串进行威胁.我在这儿?你能详细说明究竟发生了什么吗?谢谢.(注意:我对如何打印数组不感兴趣.我知道.)
get1()方法返回一个数组.我确实得到了输出,但来自的get1()是[D@addbf1
我的问题是有没有办法直接使用返回的数组来获取值inf1[0]并inf1[1]在输出语句中显示它?
我知道其他显示输出的方法.但我想知道我是否可以直接检索返回数组的元素.
class vehicle{
double [] inf1 = new double[2];
void set(double d, double s) {
inf1[0]=d;
inf1[1]=s;
}
double[] get1() {
return inf1;
}
}
public class calc2 {
public static void main(String args[]) {
vehicle ob = new vehicle();
ob.set(56.24, 75);
System.out.println("The time taken to cover "+ob.get1());
}
}
Run Code Online (Sandbox Code Playgroud)