Question

En Java, les tableaux ne remplacent pas toString(). Par conséquent, si vous essayez d’en imprimer un directement, vous obtenez le className + @ + l’hex du hashCode du tableau, tel que défini par Object.toString():

int[] intArray = new int[] {1, 2, 3, 4, 5};
System.out.println(intArray);     // prints something like '[I@3343c8b3'

Mais d'habitude, nous voudrions plutôt quelque chose qui ressemble à [1, 2, 3, 4, 5]. Quel est le moyen le plus simple de faire ça? Voici quelques exemples d'entrées et de sorties:

// 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]
Était-ce utile?

La solution

Depuis Java 5, vous pouvez utiliser Arrays.toString(arr) ou Arrays.deepToString(arr) pour les tableaux au sein des tableaux. Notez que la Object[] version appelle .toString() sur chaque objet du tableau. La sortie est même décorée de la manière exacte que vous demandez.

Exemples:

  • Tableau simple:

    String[] array = new String[] {"John", "Mary", "Bob"};
    System.out.println(Arrays.toString(array));
    

    Sortie:

    [John, Mary, Bob]
    
  • Tableau imbriqué:

    String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};
    System.out.println(Arrays.toString(deepArray));
    //output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
    System.out.println(Arrays.deepToString(deepArray));
    

    Sortie:

    [[John, Mary], [Alice, Bob]]
    
  • double Tableau:

    double[] doubleArray = { 7.0, 9.0, 5.0, 1.0, 3.0 };
    System.out.println(Arrays.toString(doubleArray));
    

    Sortie:

    [7.0, 9.0, 5.0, 1.0, 3.0 ]
    
  • int Tableau:

    int[] intArray = { 7, 9, 5, 1, 3 };
    System.out.println(Arrays.toString(intArray));
    

    Sortie:

    [7, 9, 5, 1, 3 ]
    

Autres conseils

Vérifiez toujours les bibliothèques standard en premier. Essayez:

System.out.println(Arrays.toString(array));

ou si votre tableau contient d'autres tableaux en tant qu'éléments:

System.out.println(Arrays.deepToString(array));

Cela fait plaisir à savoir, cependant, comme pour & "toujours vérifier les bibliothèques standard en premier &"; Je ne serais jamais tombé sur le truc de Arrays.toString( myarray )

- depuis que je me suis concentré sur le type de tableau pour voir comment faire cela. Je ne voulais pas avoir à parcourir la chose: je voulais un appel simple pour le faire ressembler à ce que je vois dans le débogueur Eclipse et dans myarray.toString () ne le faisait tout simplement pas.

import java.util.Arrays;
.
.
.
System.out.println( Arrays.toString( myarray ) );

Dans JDK1.8, vous pouvez utiliser des opérations d'agrégation et une expression lambda:

String[] strArray = new String[] {"John", "Mary", "Bob"};

// #1
Arrays.asList(strArray).stream().forEach(s -> System.out.println(s));

// #2
Stream.of(strArray).forEach(System.out::println);

// #3
Arrays.stream(strArray).forEach(System.out::println);

/* output:
John
Mary
Bob
*/

Si vous utilisez Java 1.4, vous pouvez plutôt faire:

System.out.println(Arrays.asList(array));

(Cela fonctionne dans la version 1.5+ aussi, bien sûr.)

À partir de Java 8, on pourrait également tirer parti de la méthode join() fournie par la Classe de chaîne pour imprimer des éléments de tableau, sans les crochets, et séparés par un délimiteur de choix (l'espace caractère de l'exemple ci-dessous):

String[] greeting = {"Hey", "there", "amigo!"};
String delimiter = " ";
String.join(delimiter, greeting) 

La sortie sera & "Hé là, amigo! &";

.

Arrays.toString

En réponse directe, la solution fournie par plusieurs, y compris @Esko , à l'aide de Arrays.toString et Arrays.deepToString méthodes , est tout simplement le meilleur.

Java 8 - Stream.collect (join ()), Stream.forEach

J'essaie ci-dessous de répertorier certaines des méthodes suggérées, en essayant de s'améliorer un peu. L'ajout le plus notable est l'utilisation du Stream.collect , à l'aide d'un opérateur < code> rejoindre Collector , pour imiter ce que fait le String.join .

int[] ints = new int[] {1, 2, 3, 4, 5};
System.out.println(IntStream.of(ints).mapToObj(Integer::toString).collect(Collectors.joining(", ")));
System.out.println(IntStream.of(ints).boxed().map(Object::toString).collect(Collectors.joining(", ")));
System.out.println(Arrays.toString(ints));

String[] strs = new String[] {"John", "Mary", "Bob"};
System.out.println(Stream.of(strs).collect(Collectors.joining(", ")));
System.out.println(String.join(", ", strs));
System.out.println(Arrays.toString(strs));

DayOfWeek [] days = { FRIDAY, MONDAY, TUESDAY };
System.out.println(Stream.of(days).map(Object::toString).collect(Collectors.joining(", ")));
System.out.println(Arrays.toString(days));

// These options are not the same as each item is printed on a new line:
IntStream.of(ints).forEach(System.out::println);
Stream.of(strs).forEach(System.out::println);
Stream.of(days).forEach(System.out::println);

Avant Java 8

Nous aurions pu utiliser Arrays.toString (tableau) pour imprimer un tableau à une dimension et Arrays.deepToString (tableau) pour des tableaux multidimensionnels.

Java 8

Nous avons maintenant l'option Stream et lambda pour imprimer le tableau.

Impression d'un tableau à une dimension:

public static void main(String[] args) {
    int[] intArray = new int[] {1, 2, 3, 4, 5};
    String[] strArray = new String[] {"John", "Mary", "Bob"};

    //Prior to Java 8
    System.out.println(Arrays.toString(intArray));
    System.out.println(Arrays.toString(strArray));

    // In Java 8 we have lambda expressions
    Arrays.stream(intArray).forEach(System.out::println);
    Arrays.stream(strArray).forEach(System.out::println);
}

Le résultat est:

  

[1, 2, 3, 4, 5]
  [John, Mary, Bob]
  1
  2
  3
  4
  5
  John
  Marie
  Bob

Impression d'un tableau multidimensionnel Juste au cas où nous voudrions imprimer un tableau multi-dimensionnel, nous pouvons utiliser Arrays.deepToString (tableau) comme:

public static void main(String[] args) {
    int[][] int2DArray = new int[][] { {11, 12}, { 21, 22}, {31, 32, 33} };
    String[][] str2DArray = new String[][]{ {"John", "Bravo"} , {"Mary", "Lee"}, {"Bob", "Johnson"} };

    //Prior to Java 8
    System.out.println(Arrays.deepToString(int2DArray));
    System.out.println(Arrays.deepToString(str2DArray));

    // In Java 8 we have lambda expressions
    Arrays.stream(int2DArray).flatMapToInt(x -> Arrays.stream(x)).forEach(System.out::println);
    Arrays.stream(str2DArray).flatMap(x -> Arrays.stream(x)).forEach(System.out::println);
} 

Le point à noter est que la méthode Arrays.stream (T []) , qui dans le cas de int [] nous renvoie Stream < int [] > puis la méthode flatMapToInt () mappe chaque élément du flux avec le contenu d'un flux mappé produit en appliquant la fonction de mappage fournie à chaque élément.

Le résultat est:

  

[[11, 12], [21, 22], [31, 32, 33]]
  [[John, Bravo], [Mary, Lee], [Bob, Johnson]]
  11
  12
  21
  22
  31
  32
  33
  John
  Bravo
  Marie
  Lee
  Bob
  Johnson

Arrays.deepToString (arr) n’imprime que sur une ligne.

int[][] table = new int[2][2];

Pour obtenir un tableau à imprimer sous forme de tableau à deux dimensions, je devais le faire:

System.out.println(Arrays.deepToString(table).replaceAll("],", "]," + System.getProperty("line.separator")));

Il semble que la méthode Arrays.deepToString (arr) devrait prendre une chaîne de séparation, mais ce n'est malheureusement pas le cas.

for(int n: someArray) {
    System.out.println(n+" ");
}

Différentes manières d'imprimer des tableaux en Java:

  1. Manière simple

    List<String> list = new ArrayList<String>();
    list.add("One");
    list.add("Two");
    list.add("Three");
    list.add("Four");
    // Print the list in console
    System.out.println(list);
    
  

Sortie:       [Un, deux, trois, quatre]

  1. Utilisation de toString ()

    String[] array = new String[] { "One", "Two", "Three", "Four" };
    System.out.println(Arrays.toString(array));
    
  

Sortie: [Un, Deux, Trois, Quatre]

  1. Tableau d'impression de tableaux

    String[] arr1 = new String[] { "Fifth", "Sixth" };
    String[] arr2 = new String[] { "Seventh", "Eight" };
    String[][] arrayOfArray = new String[][] { arr1, arr2 };
    System.out.println(arrayOfArray);
    System.out.println(Arrays.toString(arrayOfArray));
    System.out.println(Arrays.deepToString(arrayOfArray));
    
  

Sortie: [[Ljava.lang.String; @ 1ad086a [[Ljava.lang.String; @ 10385c1,   [Ljava.lang.String; @ 42719c] [[Cinquième, Sixième], [Septième, Huitième]]

Ressource: Accès Un tableau

L'utilisation de boucles régulières pour est, à mon avis, la manière la plus simple d'imprimer un tableau. Ici vous avez un exemple de code basé sur votre intArray

for (int i = 0; i < intArray.length; i++) {
   System.out.print(intArray[i] + ", ");
}

Il donne une sortie comme la vôtre     1, 2, 3, 4, 5

Je suis tombé sur ce message dans Vanilla #Java récemment. Ce n'est pas très pratique d'écrire Arrays.toString (arr); , puis d'importer tout le temps java.util.Arrays; .

Veuillez noter qu'il ne s'agit en aucun cas d'une solution permanente. Juste un hack qui peut simplifier le débogage.

L’impression d’un tableau donne directement la représentation interne et le hashCode. Maintenant, toutes les classes ont Object comme type parent. Alors, pourquoi ne pas pirater Object.toString () ? Sans modification, la classe Object ressemble à ceci:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

Et si ceci devient:

public String toString() {
    if (this instanceof boolean[])
        return Arrays.toString((boolean[]) this);
    if (this instanceof byte[])
        return Arrays.toString((byte[]) this);
    if (this instanceof short[])
        return Arrays.toString((short[]) this);
    if (this instanceof char[])
        return Arrays.toString((char[]) this);
    if (this instanceof int[])
        return Arrays.toString((int[]) this);
    if (this instanceof long[])
        return Arrays.toString((long[]) this);
    if (this instanceof float[])
        return Arrays.toString((float[]) this);
    if (this instanceof double[])
        return Arrays.toString((double[]) this);
    if (this instanceof Object[])
        return Arrays.deepToString((Object[]) this);
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

Cette classe modded peut simplement être ajoutée au chemin de classe en ajoutant les éléments suivants à la ligne de commande: -Xbootclasspath / p: cible / classes .

Maintenant, avec la disponibilité de deepToString (..) depuis Java 5, le toString (..) peut facilement être remplacé par deepToString (.. ) pour ajouter la prise en charge des tableaux contenant d'autres tableaux.

J’ai trouvé ce hack très utile et ce serait formidable si Java pouvait simplement l’ajouter. Je comprends les problèmes potentiels liés aux très grands tableaux, car les représentations de chaîne pourraient poser problème. Vous pouvez peut-être transmettre quelque chose comme un System.out ou un PrintWriter pour de telles éventualités.

Cela devrait toujours fonctionner quelle que soit la version de JDK que vous utilisez:

System.out.println(Arrays.asList(array));

Cela fonctionnera si le Tableau contient des objets. Si le Array contient des types primitifs, vous pouvez utiliser des classes wrapper au lieu de stocker la primitive directement sous la forme ..

Exemple:

int[] a = new int[]{1,2,3,4,5};

Remplacez-le par:

Integer[] a = new Integer[]{1,2,3,4,5};

Mise à jour:

Oui! il convient de mentionner que la conversion d'un tableau en un tableau d'objets OU pour utiliser le tableau d'objets est coûteuse et peut ralentir l'exécution. cela se produit par la nature de Java appelée autoboxing.

Donc, uniquement à des fins d'impression, il ne devrait pas être utilisé. nous pouvons créer une fonction qui prend un tableau en paramètre et affiche le format souhaité sous la forme

public void printArray(int [] a){
        //write printing code
} 

En Java 8, c’est facile. il y a deux mots-clés

  1. flux: Arrays.stream (intArray) .forEach
  2. référence de la méthode: :: println

    int[] intArray = new int[] {1, 2, 3, 4, 5};
    Arrays.stream(intArray).forEach(System.out::println);
    

Si vous souhaitez imprimer tous les éléments du tableau sur la même ligne, utilisez simplement print au lieu de println i.e.

int[] intArray = new int[] {1, 2, 3, 4, 5};
Arrays.stream(intArray).forEach(System.out::print);

Une autre manière sans référence à la méthode consiste simplement à utiliser:

int[] intArray = new int[] {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(intArray));

Il existe un moyen supplémentaire si votre tableau est de type char []:

char A[] = {'a', 'b', 'c'}; 

System.out.println(A); // no other arguments

imprime

abc

Pour ajouter à toutes les réponses, l'impression de l'objet sous forme de chaîne JSON est également une option.

Utilisation de Jackson:

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
System.out.println(ow.writeValueAsString(anyArray));

Utilisation de Gson:

Gson gson = new Gson();
System.out.println(gson.toJson(anyArray));

Voici un raccourci simplifié que j'ai essayé:

    int x[] = {1,2,3};
    String printableText = Arrays.toString(x).replaceAll("[\\[\\]]", "").replaceAll(", ", "\n");
    System.out.println(printableText);

Cela va imprimer

1
2
3

Aucune boucle requise dans cette approche et il est préférable de ne placer que de petits tableaux

Vous pouvez parcourir le tableau en imprimant chaque élément au fur et à mesure. Par exemple:

String[] items = {"item 1", "item 2", "item 3"};

for(int i = 0; i < items.length; i++) {

    System.out.println(items[i]);

}

Sortie:

item 1
item 2
item 3

Il existe un moyen d'imprimer un groupe

 // 1) toString()  
    int[] arrayInt = new int[] {10, 20, 30, 40, 50};  
    System.out.println(Arrays.toString(arrayInt));

// 2 for loop()
    for (int number : arrayInt) {
        System.out.println(number);
    }

// 3 for each()
    for(int x: arrayInt){
         System.out.println(x);
     }
public class printer {

    public static void main(String[] args) {
        String a[] = new String[4];
        Scanner sc = new Scanner(System.in);
        System.out.println("enter the data");
        for (int i = 0; i < 4; i++) {
            a[i] = sc.nextLine();
        }
        System.out.println("the entered data is");
        for (String i : a) {
            System.out.println(i);
        }
      }
    }

L'utilisation des méthodes org.apache.commons.lang3.StringUtils.join (*) peut être une option
Par exemple:

String[] strArray = new String[] { "John", "Mary", "Bob" };
String arrayAsCSV = StringUtils.join(strArray, " , ");
System.out.printf("[%s]", arrayAsCSV);
//output: [John , Mary , Bob]

J'ai utilisé la dépendance suivante

<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>

Vous pouvez également utiliser la boucle For-each pour imprimer des éléments du tableau:

int array[] = {1, 2, 3, 4, 5};
for (int i:array)
    System.out.println(i);

Ceci est marqué comme un doublon pour imprimer une octet [] . Remarque: pour un tableau d'octets, il existe des méthodes supplémentaires qui peuvent être appropriées.

Vous pouvez l’imprimer sous forme de chaîne s’il contient des caractères ISO-8859-1.

String s = new String(bytes, StandardChars.ISO_8559);
System.out.println(s);
// to reverse
byte[] bytes2 = s.getBytes(StandardChars.ISO_8559);

ou s'il contient une chaîne UTF-8

String s = new String(bytes, StandardChars.UTF_8);
System.out.println(s);
// to reverse
byte[] bytes2 = s.getBytes(StandardChars.UTF_8);

ou si vous souhaitez l’imprimer en hexadécimal.

String s = DatatypeConverter.printHexBinary(bytes);
System.out.println(s);
// to reverse
byte[] bytes2 = DatatypeConverter.parseHexBinary(s);

ou si vous souhaitez l’imprimer en base64.

String s = DatatypeConverter.printBase64Binary(bytes);
System.out.println(s);
// to reverse
byte[] bytes2 = DatatypeConverter.parseBase64Binary(s);

ou si vous souhaitez imprimer un tableau de valeurs d'octets signés

String s = Arrays.toString(bytes);
System.out.println(s);
// to reverse
String[] split = s.substring(1, s.length() - 1).split(", ");
byte[] bytes2 = new byte[split.length];
for (int i = 0; i < bytes2.length; i++)
    bytes2[i] = Byte.parseByte(split[i]);

ou si vous souhaitez imprimer un tableau de valeurs d'octets non signés

String s = Arrays.toString(
               IntStream.range(0, bytes.length).map(i -> bytes[i] & 0xFF).toArray());
System.out.println(s);
// to reverse
String[] split = s.substring(1, s.length() - 1).split(", ");
byte[] bytes2 = new byte[split.length];
for (int i = 0; i < bytes2.length; i++)
    bytes2[i] = (byte) Integer.parseInt(split[i]); // might need a range check.
// array of primitives:
int[] intArray = new int[] {1, 2, 3, 4, 5};

System.out.println(Arrays.toString(intArray));

output: [1, 2, 3, 4, 5]
// array of object references:
String[] strArray = new String[] {"John", "Mary", "Bob"};

System.out.println(Arrays.toString(strArray));

output: [John, Mary, Bob]

En Java 8:

Arrays.stream(myArray).forEach(System.out::println);

Il existe plusieurs manières d’imprimer un tableau d’éléments.Tout d’abord, je vais expliquer ce qu’est un tableau? .. Le tableau est une structure de données simple qui permet de stocker des données. Lorsque vous définissez un tableau, blocs de mémoire auxiliaires dans la RAM.Ces blocs de mémoire sont pris d’une unité.

Ok, je vais créer un tableau comme celui-ci,

class demo{
      public static void main(String a[]){

           int[] number={1,2,3,4,5};

           System.out.print(number);
      }
}

Maintenant, regardez le résultat,

 entrer la description de l'image ici

Vous pouvez voir une chaîne inconnue imprimée. Comme je l’ai déjà mentionné, l’adresse mémoire dont le tableau (nombre tableau) déclaré est imprimé est imprimée. Si vous souhaitez afficher les éléments du tableau, vous pouvez utiliser "for for". , comme ça ..

class demo{
      public static void main(String a[]){

           int[] number={1,2,3,4,5};

           int i;

           for(i=0;i<number.length;i++){
                 System.out.print(number[i]+"  ");
           }
      }
}

Maintenant, regardez le résultat,

 entrer la description de l'image ici

Ok, éléments d'un tableau de dimensions imprimé avec succès..Maintenant, je vais considérer un tableau à deux dimensions..Je vais déclarer un tableau à deux dimensions sous la forme "nombre2". et imprimez les éléments à l'aide de "Arrays.deepToString ()". mot-clé.Avant de l'utiliser, vous devrez importer la bibliothèque 'java.util.Arrays'.

 import java.util.Arrays;

 class demo{
      public static void main(String a[]){

           int[][] number2={{1,2},{3,4},{5,6}};`

           System.out.print(Arrays.deepToString(number2));
      }
}

considérez la sortie,

 entrer la description de l'image ici

En même temps, en utilisant deux boucles for, vous pouvez imprimer des éléments 2D..Merci!

si vous utilisez jdk 8.

public static void print(int[] array) {
    StringJoiner joiner = new StringJoiner(",", "[", "]");
    Arrays.stream(array).forEach(element -> joiner.add(element + ""));
    System.out.println(joiner.toString());
}


int[] array = new int[]{7, 3, 5, 1, 3};
print(array);

sortie:

[7,3,5,1,3]

Si vous utilisez la bibliothèque Commons.Lang , nous pourrions procéder comme suit:

ArrayUtils.toString (array)

int[] intArray = new int[] {1, 2, 3, 4, 5};
String[] strArray = new String[] {"John", "Mary", "Bob"};
ArrayUtils.toString(intArray);
ArrayUtils.toString(strArray);

Sortie:

{1,2,3,4,5}
{John,Mary,Bob}

Si vous souhaitez imprimer, évaluez le contenu d'un tableau de cette manière. Vous pouvez utiliser Arrays.toString

.
jshell> String[] names = {"ram","shyam"};
names ==> String[2] { "ram", "shyam" }

jshell> Arrays.toString(names);
$2 ==> "[ram, shyam]"

jshell> 
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top