أساليب صفيف جافا - كيفية طباعة صفيف في جافا
المصفوفة هي بنية بيانات تُستخدم لتخزين البيانات من نفس النوع. تخزن المصفوفات عناصرها في مواقع ذاكرة متجاورة.
في Java ، المصفوفات هي كائنات. يمكن استدعاء جميع وظائف كائن الفئة في مصفوفة. يمكننا تخزين عدد ثابت من العناصر في مصفوفة.
دعنا نعلن عن نوع بدائي بسيط من المصفوفة:
int[] intArray = {2,5,46,12,34};
لنحاول الآن طباعته System.out.println()
بالطريقة التالية:
System.out.println(intArray); // output: [[email protected]
لماذا لم تطبع Java نظامنا؟ ماذا يحدث تحت الغطاء؟
تقوم System.out.println()
الطريقة بتحويل الكائن الذي مررناه إلى سلسلة عن طريق الاستدعاء String.valueOf()
. إذا نظرنا إلى String.valueOf()
تنفيذ الطريقة ، فسنرى هذا:
public static String valueOf(Object obj) { return (obj == null) ? "null" : obj.toString(); }
إذا كان الكائن الذي تم تمريره هو null
إرجاع فارغ ، وإلا فإنه يستدعي obj.toString()
. في نهاية المطاف ، System.out.println()
يدعو toString()
لطباعة الإخراج.
إذا كانت فئة هذا الكائن لا تلغي Object.toString()
تطبيق ، فسوف تستدعي Object.toString()
الطريقة.
Object.toString()
العوائد . بعبارات بسيطة ، تقوم بإرجاع: "كود تجزئة اسم الفئة @ الكائن".getClass().getName()+‘@’+Integer.toHexString(hashCode())
في مخرجاتنا السابقة [[email protected]
، [
تنص على أن هذه مصفوفة I
وترمز إلى int (نوع المصفوفة). 74a14482
هو التمثيل السداسي العشري غير الموقع لرمز التجزئة الخاص بالمصفوفة.
عندما نقوم بإنشاء فئات مخصصة خاصة بنا ، فمن الأفضل تجاوز Object.toString()
الطريقة.
لا يمكننا طباعة المصفوفات في Java باستخدام System.out.println()
طريقة بسيطة . بدلاً من ذلك ، هذه هي الطرق التالية التي يمكننا من خلالها طباعة مصفوفة:
- الحلقات: for loop و for-each loop
Arrays.toString()
طريقةArrays.deepToString()
طريقةArrays.asList()
طريقة- واجهة Java Iterator
- Java Stream API
دعونا نراهم واحدا تلو الآخر.
1. الحلقات: for loop و for-each loop
فيما يلي مثال على حلقة for:
int[] intArray = {2,5,46,12,34}; for(int i=0; i
All wrapper classes override
Object.toString()
and return a string representation of their value.
And here's a for-each loop:
int[] intArray = {2,5,46,12,34}; for(int i: intArray){ System.out.print(i); // output: 25461234 }
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.
Array elements are converted to strings using the
String.valueOf()
method, like this:
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.
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.
For example:
// creating multidimensional array int[][] multiDimensionalArr = { {2,3}, {5,9} }; System.out.println(Arrays.toString(multiDimensionalArr)); // output: [[[email protected], [[email protected]]
With the help of
Arrays.deepToString()
, we can print multidimensional arrays.
3. Arrays.deepToString() method
Arrays.deepToString()
returns a string representation of the “deep contents” of the specified array.
If an element is an array of primitive type, it is converted to a string by invoking the appropriate overloading of
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.
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.
If you are curious as to how it does recursion, here is the source code for the
Arrays.deepToString()
method.
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() 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.
Java calls
Arrays.asList(intArray).toString()
. This technique internally uses the toString()
method of the type of the elements within the list.
Another example with our custom Teacher class:
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 Iterator Interface
Similar to a for-each loop, we can use the Iterator interface to loop through array elements and print them.
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.
Here is an example of how we can print an array using the Iterator interface:
Integer[] intArray = {2,5,46,12,34}; // creating a List of Integer List list = Arrays.asList(intArray); // creating an iterator of Integer List Iterator it = list.iterator(); // if List has elements to be iterated while(it.hasNext()) { System.out.print(it.next()); // output: 25461234 }
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.
With the help of the
forEach()
terminal operation we can iterate through every element of the stream.
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.
Thank you for reading.
Cover image by Aziz Acharki on Unsplash.
You can read my other articles on Medium.
Happy Coding!