java中打印数组的方法_Java数组方法–如何在Java中打印数组

java中打印数组的方法_Java数组方法–如何在Java中打印数组java中打印数组的方法Anarrayisadatastructureusedtostoredataofthesametype.Arraysstoretheirelementsincontiguousmemorylocations.数组是用于存储相同类型数据的数据结构。数组将其元素存储在连续的内存位置中。InJava,arraysareo…

大家好,又见面了,我是你们的朋友全栈君。

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中打印数组。 相反,以下是我们可以打印数组的以下方法:

  1. Loops: for loop and for-each loop

    循环:for循环和for-each循环

  2. Arrays.toString() method

    Arrays.toString()方法

  3. Arrays.deepToString() method

    Arrays.deepToString()方法

  4. Arrays.asList() method

    Arrays.asList()方法

  5. Java Iterator interface

    Java Iterator接口

  6. 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 AcharkiUnsplash拍摄

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中打印数组的方法

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/136766.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 泰勒展开式「建议收藏」

    泰勒展开式「建议收藏」数学中,泰勒公式是一个用函数在某点的信息描述其附近取值的公式。如果函数足够平滑的话,在已知函数在某一点的各阶导数值的情况之下,泰勒公式可以用这些导数值做系数构建一个多项式来近似函数在这一点的邻域中的值

    2022年8月2日
    2
  • 基于Deep Learning 的视频识别技术「建议收藏」

    基于Deep Learning 的视频识别技术「建议收藏」深度学习在最近十来年特别火,几乎是带动AI浪潮的最大贡献者。互联网视频在最近几年也特别火,短视频、视频直播等各种新型UGC模式牢牢抓住了用户的消费心里,成为互联网吸金的又一利器。当这两个火碰在一起,会产生什么样的化学反应呢?不说具体的技术,先上一张福利图,该图展示了机器对一个视频的认知效果。其总红色的字表示objects,蓝色的字表示scen…

    2022年5月27日
    25
  • SpiderData 2019年1月31日 DApp数据排行榜[通俗易懂]

    SpiderData 2019年1月31日 DApp数据排行榜[通俗易懂]SpiderData 2019年1月31日 DApp数据排行榜

    2022年4月21日
    50
  • CPU分支预测_流水线条件分支

    CPU分支预测_流水线条件分支文章目录1.CPU指令流水线2.分支预测的方法2.1分支预测的作用2.2分支预测的方法2.2.1静态预测2.2.2动态预测2.2.3其它预测3.分支预测的实例1.CPU指令流水线CPU在执行指令的时候,一条指令并不是一下就完成的,会有生命周期,例如很经典的有MIPS五级流水线,一条指令执行完毕需要五步取指(instructionfetch):将指令从存储器里面取出来译码(instructiondecode):将指令从存储器中读取出来执行(instructionexecute)

    2022年8月20日
    9
  • 阿里云设置端口访问、使用_阿里云服务器端口号

    阿里云设置端口访问、使用_阿里云服务器端口号登录阿里云账号后,点击控制台点击自定义视图→再点击云服务器ECS点击实例id进入实例:点击本实例安全组:点击安全组id或者配置规则进入安全组规则配置界面,可以选择添加方式,这里以手动添加作为演示点击手动添加后,会出现添加栏,我们配置521端口,源选择0.0.0.0/0(意思是开放给所有人),最后点击保存放行端口就设置完毕了此外也可以从另一个地方进入本地实例安全组:(1)点击云服务器ECS后(上述步骤3)进入实例页面后,可以直接点击实例(2)选择自..

    2022年10月3日
    0
  • 单隐层前馈神经网络网络构造_前馈型神经网络常用于

    单隐层前馈神经网络网络构造_前馈型神经网络常用于这篇博客主要介绍神经网络基础,单隐层前馈神经网络与反向传播算法。神经网络故名思议是由人的神经系统启发而得来的一种模型。神经网络可以用来做分类和回归等任务,其具有很好的非线性拟合能力。接下来我们就来详细介绍一下但隐层前馈神经网络。首先我们来看一下神经元的数学模型,如下图所示:可以看到为输入信号,而神经元最终输出为,由此我们可以看到,单个神经元是多输入单输出的。但是从上图我们可以看到,…

    2022年10月30日
    0

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号