大家好,又见面了,我是你们的朋友全栈君。
java中打印数组的方法
An array is a data structure used to store data of the same type. Arrays store their elements in contiguous memory locations.
数组是用于存储相同类型数据的数据结构。 数组将其元素存储在连续的内存位置中。
In Java, arrays are objects. All methods of class object may be invoked in an array. We can store a fixed number of elements in an array.
在Java中,数组是对象。 类对象的所有方法都可以在数组中调用。 我们可以在数组中存储固定数量的元素。
Let’s declare a simple primitive type of array:
让我们声明一个简单的原始数组类型:
int[] intArray = {2,5,46,12,34};
Now let’s try to print it with the System.out.println()
method:
现在,让我们尝试使用System.out.println()
方法进行打印:
System.out.println(intArray);
// output: [I@74a14482
Why did Java not print our array? What is happening under the hood?
为什么Java不打印我们的数组? 幕后发生了什么?
The System.out.println()
method converts the object we passed into a string by calling String.valueOf()
. If we look at the String.valueOf()
method’s implementation, we’ll see this:
System.out.println()
方法通过调用String.valueOf()
将传递给我们的对象转换为字符串。 如果我们查看String.valueOf()
方法的实现,将会看到以下内容:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
If the passed-in object is null
it returns null, else it calls obj.toString()
. Eventually, System.out.println()
calls toString()
to print the output.
如果传入的对象为null
则返回null,否则调用obj.toString()
。 最终, System.out.println()
调用toString()
来打印输出。
If that object’s class does not override Object.toString()
‘s implementation, it will call the Object.toString()
method.
如果该对象的类未覆盖Object.toString()
的实现,它将调用Object.toString()
方法。
Object.toString()
returns getClass().getName()+‘@’+Integer.toHexString(hashCode())
. In simple terms, it returns: “class name @ object’s hash code”.
Object.toString()
返回getClass().getName()+ '@' +Integer.toHexString(hashCode())
。 简单来说,它返回:“类名@对象的哈希码”。
In our previous output [I@74a14482
, the [
states that this is an array, and I
stands for int (the type of the array). 74a14482
is the unsigned hexadecimal representation of the hash code of the array.
在我们之前的输出[I@74a14482
, [
声明这是一个数组,而I
代表int(数组的类型)。 74a14482
是数组的哈希码的无符号十六进制表示形式。
Whenever we are creating our own custom classes, it is a best practice to override the Object.toString()
method.
每当我们创建自己的自定义类时,最佳做法是重写Object.toString()
方法。
We can not print arrays in Java using a plain System.out.println()
method. Instead, these are the following ways we can print an array:
我们无法使用普通的System.out.println()
方法在Java中打印数组。 相反,以下是我们可以打印数组的以下方法:
- Loops: for loop and for-each loop
循环:for循环和for-each循环
Arrays.toString()
methodArrays.toString()
方法-
Arrays.deepToString()
methodArrays.deepToString()
方法 -
Arrays.asList()
methodArrays.asList()
方法 - Java Iterator interface
Java Iterator接口
- Java Stream API
Java Stream API
Let’s see them one by one.
让我们一一看。
1.循环:for循环和for-each循环 (1. Loops: for loop and for-each loop)
Here’s an example of a for loop:
这是一个for循环的示例:
int[] intArray = {2,5,46,12,34};
for(int i=0; i<intArray.length; i++){
System.out.print(intArray[i]);
// output: 25461234
}
All wrapper classes override Object.toString()
and return a string representation of their value.
所有包装器类均重写Object.toString()
并返回其值的字符串表示形式。
And here’s a for-each loop:
这是一个for-each循环:
int[] intArray = {2,5,46,12,34};
for(int i: intArray){
System.out.print(i);
// output: 25461234
}
2. Arrays.toString()方法 (2. Arrays.toString() method)
Arrays.toString()
is a static method of the array class which belongs to the java.util
package. It returns a string representation of the contents of the specified array. We can print one-dimensional arrays using this method.
Arrays.toString()
是属于java.util
包的数组类的静态方法。 它返回指定数组内容的字符串表示形式。 我们可以使用这种方法打印一维数组。
Array elements are converted to strings using the String.valueOf()
method, like this:
数组元素使用String.valueOf()
方法转换为字符串,如下所示:
int[] intArray = {2,5,46,12,34};
System.out.println(Arrays.toString(intArray));
// output: [2, 5, 46, 12, 34]
For a reference type of array, we have to make sure that the reference type class overrides the Object.toString()
method.
对于数组的引用类型,我们必须确保引用类型类重写Object.toString()
方法。
For example:
例如:
public class Test {
public static void main(String[] args) {
Student[] students = {new Student("John"), new Student("Doe")};
System.out.println(Arrays.toString(students));
// output: [Student{name='John'}, Student{name='Doe'}]
}
}
class Student {
private String name;
public Student(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student{" + "name='" + name + '\'' + '}';
}
}
This method is not appropriate for multidimensional arrays. It converts multidimensional arrays to strings using Object.toString()
which describes their identities rather than their contents.
此方法不适用于多维数组。 它使用Object.toString()
将多维数组转换为字符串,该数组描述其标识而不是其内容。
For example:
例如:
// creating multidimensional array
int[][] multiDimensionalArr = { {2,3}, {5,9} };
System.out.println(Arrays.toString(multiDimensionalArr));
// output: [[I@74a14482, [I@1540e19d]
With the help of Arrays.deepToString()
, we can print multidimensional arrays.
借助Arrays.deepToString()
,我们可以打印多维数组。
3. Arrays.deepToString()方法 (3. Arrays.deepToString() method)
Arrays.deepToString()
returns a string representation of the “deep contents” of the specified array.
Arrays.deepToString()
返回指定数组的“深层内容”的字符串表示形式。
If an element is an array of primitive type, it is converted to a string by invoking the appropriate overloading of Arrays.toString()
.
如果元素是原始类型的数组,则通过调用Arrays.toString()
的适当重载将其转换为字符串。
Here is an example of the primitive type of multidimensional array:
这是多维数组的原始类型的示例:
// creating multidimensional array
int[][] multiDimensionalArr = { {2,3}, {5,9} };
System.out.println(Arrays.deepToString(multiDimensionalArr));
// output: [[2, 3], [5, 9]]
If an element is an array of reference type, it is converted to a string by invoking Arrays.deepToString()
recursively.
如果元素是引用类型的数组,则通过递归调用Arrays.deepToString()
将其转换为字符串。
Teacher[][] teachers =
{
{ new Teacher("John"), new Teacher("David") }, {new Teacher("Mary")} };
System.out.println(Arrays.deepToString(teachers));
// output:
[[Teacher{name='John'}, Teacher{name='David'}],[Teacher{name='Mary'}]]
We have to override Object.toString()
in our Teacher class.
我们必须在Teacher类中重写Object.toString()
。
If you are curious as to how it does recursion, here is the source code for the Arrays.deepToString()
method.
如果您对递归的执行方式感到好奇,则这里是Arrays.deepToString()
方法的源代码 。
NOTE: Reference type one-dimensional arrays can also be printed using this method. For example:
注意:引用类型的一维数组也可以使用此方法进行打印。 例如:
Integer[] oneDimensionalArr = {1,4,7};
System.out.println(Arrays.deepToString(oneDimensionalArr));
// output: [1, 4, 7]
4. Arrays.asList()方法 (4. Arrays.asList() method)
This method returns a fixed-size list backed by the specified array.
此方法返回由指定数组支持的固定大小的列表。
Integer[] intArray = {2,5,46,12,34};
System.out.println(Arrays.asList(intArray));
// output: [2, 5, 46, 12, 34]
We have changed the type to Integer from int, because List is a collection that holds a list of objects. When we are converting an array to a list it should be an array of reference type.
我们将类型从int更改为Integer,因为List是一个保存对象列表的集合。 当我们将数组转换为列表时,它应该是引用类型的数组。
Java calls Arrays.asList(intArray).toString()
. This technique internally uses the toString()
method of the type of the elements within the list.
Java调用Arrays. asList (intArray).toString()
Arrays. asList (intArray).toString()
。 此技术在内部使用列表中元素类型的toString()
方法。
Another example with our custom Teacher class:
我们的自定义Teacher类的另一个示例:
Teacher[] teacher = { new Teacher("John"), new Teacher("Mary") };
System.out.println(Arrays.asList(teacher));
// output: [Teacher{name='John'}, Teacher{name='Mary'}]
NOTE: We can not print multi-dimensional arrays using this method. For example:
注意:我们不能使用此方法打印多维数组。 例如:
Teacher[][] teachers =
{
{ new Teacher("John"), new Teacher("David") }, { new Teacher("Mary") }};
System.out.println(Arrays.asList(teachers));
// output: [[Lcom.thano.article.printarray.Teacher;@1540e19d, [Lcom.thano.article.printarray.Teacher;@677327b6]
5. Java迭代器接口 (5. Java Iterator Interface)
Similar to a for-each loop, we can use the Iterator interface to loop through array elements and print them.
类似于for-each循环,我们可以使用Iterator接口循环遍历数组元素并打印它们。
Iterator object can be created by invoking the iterator()
method on a Collection. That object will be used to iterate over that Collection’s elements.
可以通过在Collection上调用iterator()
方法来创建Iterator对象。 该对象将用于遍历该Collection的元素。
Here is an example of how we can print an array using the Iterator interface:
这是一个如何使用Iterator接口打印数组的示例:
Integer[] intArray = {2,5,46,12,34};
// creating a List of Integer
List<Integer> list = Arrays.asList(intArray);
// creating an iterator of Integer List
Iterator<Integer> it = list.iterator();
// if List has elements to be iterated
while(it.hasNext()) {
System.out.print(it.next());
// output: 25461234
}
6. Java Stream API (6. Java Stream API)
The Stream API is used to process collections of objects. A stream is a sequence of objects. Streams don’t change the original data structure, they only provide the result as per the requested operations.
Stream API用于处理对象的集合。 流是一系列对象。 流不更改原始数据结构,它们仅根据请求的操作提供结果。
With the help of the forEach()
terminal operation we can iterate through every element of the stream.
借助forEach()
终端操作,我们可以迭代流中的每个元素。
For example:
例如:
Integer[] intArray = {2,5,46,12,34};
Arrays.stream(intArray).forEach(System.out::print);
// output: 25461234
Now we know how to print an array in Java.
现在我们知道了如何用Java打印数组。
Thank you for reading.
感谢您的阅读。
Cover image by Aziz Acharki on Unsplash.
封面图片由Aziz Acharki在Unsplash上拍摄 。
You can read my other articles on Medium.
您可以在Medium阅读我的其他文章。
Happy Coding!
编码愉快!
翻译自: https://www.freecodecamp.org/news/java-array-methods-how-to-print-an-array-in-java/
java中打印数组的方法
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/136766.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...