문제

Java,배열,재정의하지 않습니다 toString(), 도록,인쇄하려고 하면 하나는 바로,당신은 당신을 얻을 className+@+hex 의 hashCode 의 배열로에 의해 정의 Object.toString():

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

그러나 일반적으로 우리가 실제로 원하는 무언가가 더 [1, 2, 3, 4, 5].What's 는 가장 간단한 방법을 하고 있는가?여기에 몇 가지 예를 입력 및 출력:

// 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]
도움이 되었습니까?

해결책

Java 5이므로 사용할 수 있습니다 Arrays.toString(arr) 또는 Arrays.deepToString(arr) 배열 내 배열의 경우. 주목하십시오 Object[] 버전 호출 .toString() 배열의 각 객체에서. 출력은 당신이 요구하는 정확한 방식으로 장식되어 있습니다.

예 :

  • 간단한 배열 :

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

    산출:

    [John, Mary, Bob]
    
  • 중첩 어레이 :

    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));
    

    산출:

    [[John, Mary], [Alice, Bob]]
    
  • double 정렬:

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

    산출:

    [7.0, 9.0, 5.0, 1.0, 3.0 ]
    
  • int 정렬:

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

    산출:

    [7, 9, 5, 1, 3 ]
    

다른 팁

항상 표준 라이브러를 먼저 확인하십시오. 노력하다:

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

또는 배열에 다른 배열이 요소로 포함 된 경우 :

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

그러나 이것은 "항상 표준 라이브러리를 먼저 확인하십시오"에 대해 알아두면 좋습니다. Arrays.toString( myarray )

-나는 이것을하는 방법을보기 위해 myArray의 유형에 집중하고 있었기 때문에. 나는 그 일을 반복하고 싶지 않았다 : 나는 Eclipse Debugger와 MyArray.tostring ()에서 내가 보지 못한 것과 비슷하게 나오기 위해 쉽게 전화를 걸고 싶었다.

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

JDK1.8에서는 집계 작업과 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
*/

Java 1.4를 사용하는 경우 대신 할 수 있습니다.

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

(물론 이것은 1.5+에서도 작동합니다.)

Java 8부터 시작하여 join() method provided by the 문자열 클래스 배열 요소, 괄호가없는 배열 요소를 인쇄하고 선택의 구분 기자로 분리하려면 (아래 표시된 예제의 공간 문자) :

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

출력은 "이봐 Amigo!"입니다.

Arrays.tostring

직접적인 답으로 @ESKO를 포함하여 몇몇이 제공하는 솔루션, 사용 Arrays.toString 그리고 Arrays.deepToString 방법은 단순히 최고입니다.

Java 8- stream.collect (joining ()), stream.foreach

아래에는 제안 된 다른 방법 중 일부를 나열하려고 노력하고 약간 개선하려고 시도하며 가장 주목할만한 추가 기능은 Stream.collect 연산자, a joining Collector, 무엇을 모방하기 위해 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);

Java 8 이전

우리는 사용할 수있었습니다 Arrays.toString(array) 1 차원 배열을 인쇄합니다 Arrays.deepToString(array) 다차원 배열 용.

Java 8

이제 우리는 옵션을 얻었습니다 Stream 그리고 lambda 배열을 인쇄합니다.

1 차원 배열 인쇄 :

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);
}

출력은 다음과 같습니다.

[1, 2, 3, 4, 5]
존, 메리, 밥
1
2
3
4
5
남자
메리
단발

다차원 배열 인쇄다차 차원 배열을 인쇄하고 싶은 경우를 대비하여 사용할 수 있습니다. Arrays.deepToString(array) 처럼:

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);
} 

이제 관찰해야 할 사항은 방법입니다 Arrays.stream(T[]), 경우 int[] 우리를 반환합니다 Stream<int[]> 그런 다음 방법 flatMapToInt() 제공된 맵핑 함수를 각 요소에 적용하여 생성 된 매핑 스트림의 내용으로 각 스트림 요소를 맵핑합니다.

출력은 다음과 같습니다.

[[11, 12], [21, 22], [31, 32, 33]]
[John, Bravo], [Mary, Lee], [Bob, Johnson]
11
12
21
22
31
32
33
남자
브라보
메리
이씨
단발
존슨

Arrays.deepToString(arr) 한 줄만 인쇄합니다.

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

실제로 2 차원 테이블로 인쇄 할 테이블을 얻으려면 다음을 수행해야했습니다.

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

그것은 것 같습니다 Arrays.deepToString(arr) 메소드는 분리기 문자열을 가져와야하지만 불행히도 그렇지 않습니다.

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

자바에서 배열을 인쇄하는 다양한 방법 :

  1. 간단한 방법

    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);
    

출력 : [1, 2, 3, 4

  1. 사용 toString()

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

출력 : [1, 2, 3, 4

  1. 배열 인쇄 배열

    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));
    

출력 : [[ljava.lang.string;@1ad086a [[ljava.lang.string;@10385c1, [ljava.lang.string;@42719c] [[5 번째, 여섯 번째], [Seventh, eighth]]

자원: 배열에 액세스하십시오

정기적으로 사용합니다 ~을 위한 루프는 제 생각에 배열을 인쇄하는 가장 간단한 방법입니다. 여기에는 intarray를 기반으로 한 샘플 코드가 있습니다.

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

그것은 당신의 1, 2, 3, 4, 5로 출력을 제공합니다.

나는이 게시물을 발견했다 바닐라 #java 최근에. 글쓰기는 그리 편리하지 않습니다 Arrays.toString(arr);, 그런 다음 가져 오기 java.util.Arrays; 항상.

이것은 어떤 식 으로든 영구적 인 수정이 아닙니다. 디버깅을 더 간단하게 만들 수있는 핵 만 있습니다.

배열을 직접 인쇄하면 내부 표현과 해시 코드가 나타납니다. 이제 모든 수업에는 있습니다 Object 부모 유형으로. 따라서 해킹하지 마십시오 Object.toString()? 수정없이 객체 클래스는 다음과 같습니다.

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

이것이 바뀌면 다음과 같이 변경됩니다.

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());
}

이 modded 클래스는 다음을 명령 줄에 추가하여 클래스 경로에 추가 될 수 있습니다. -Xbootclasspath/p:target/classes.

이제 가용성이 있습니다 deepToString(..) Java 5 이후 toString(..) 쉽게 변경할 수 있습니다 deepToString(..) 다른 배열이 포함 된 배열에 대한 지원을 추가합니다.

나는 이것이 매우 유용한 해킹 인 것을 발견했으며 Java가 단순히 이것을 추가 할 수 있다면 좋을 것입니다. 문자열 표현이 문제가 될 수 있으므로 배열이 매우 큰 경우 잠재적 인 문제를 이해합니다. 어쩌면 A와 같은 것을 통과 할 수도 있습니다 System.out또는 a PrintWriter 그러한 사건을 위해.

사용하는 JDK 버전이 항상 작동해야합니다.

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

경우 작동합니다 Array 개체가 포함되어 있습니다. 만약 Array 원시 유형이 포함되어 있으면 원시를 직접 저장하는 대신 래퍼 클래스를 사용할 수 있습니다.

예시:

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

대체 : :

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

업데이트 :

예 ! 이는 배열을 객체 배열로 변환하거나 객체의 배열을 사용하는 것이 비용이 많이 들고 실행 속도가 느려질 수 있습니다. 그것은자가 옥싱이라는 Java의 본질에 의해 발생합니다.

따라서 인쇄 목적으로 만 사용해서는 안됩니다. 배열을 매개 변수로 취하고 원하는 형식을 다음과 같이 인쇄하는 함수를 만들 수 있습니다.

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

Java8 그것은 쉽습니다.두 가지 키워드

  1. 스트림: Arrays.stream(intArray).forEach
  2. 방법은 참고: ::println

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

인쇄하려면 모든 요소를 배열에서 같은 줄에,다음 사용 printprintln

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

또 다른 방법은 없는 방법을 참조 사용:

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

배열 유형이 char [] 인 경우 한 가지 추가 방법이 있습니다.

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

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

인쇄물

abc

모든 답변을 추가하려면 객체를 JSON 문자열로 인쇄하는 것도 옵션입니다.

잭슨 사용 :

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

GSON 사용 :

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

내가 시도한 단순화 된 단축키는 다음과 같습니다.

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

인쇄됩니다

1
2
3

이 접근법에서는 루프가 필요하지 않으며 작은 배열에만 적합합니다.

루프 할 때 배열을 통과하여 각 항목을 인쇄 할 수 있습니다. 예를 들어:

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

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

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

}

산출:

item 1
item 2
item 3

배열을 인쇄하는 방법이 있습니다

 // 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);
        }
      }
    }

org.apache.commons.lang3.stringutils.join (*) 메소드 사용 옵션이 될 수 있습니다.
예를 들어:

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

다음의 종속성을 사용했습니다

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

for-each 루프를 사용하여 배열의 요소를 인쇄 할 수도 있습니다.

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

이것은 중복으로 표시됩니다 바이트 인쇄 [. 참고 : 바이트 배열의 경우 적절한 추가 방법이 있습니다.

ISO-8859-1 숯이 포함 된 경우 문자열로 인쇄 할 수 있습니다.

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

또는 UTF-8 문자열이 포함 된 경우

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

또는 당신이 그것을 16 진수로 인쇄하고 싶다면.

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

또는 Base64로 인쇄하려는 경우.

String s = DatatypeConverter.printBase64Binary(bytes);
System.out.println(s);
// to reverse
byte[] bytes2 = DatatypeConverter.parseBase64Binary(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]);

또는 서명되지 않은 바이트 값 배열을 인쇄하려면

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]

In java 8 :

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

There are several ways to print an array elements.First of all, I'll explain that, what is an array?..Array is a simple data structure for storing data..When you define an array , Allocate set of ancillary memory blocks in RAM.Those memory blocks are taken one unit ..

Ok, I'll create an array like this,

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

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

           System.out.print(number);
      }
}

Now look at the output,

enter image description here

You can see an unknown string printed..As I mentioned before, the memory address whose array(number array) declared is printed.If you want to display elements in the array, you can use "for loop " , like this..

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]+"  ");
           }
      }
}

Now look at the output,

enter image description here

Ok,Successfully printed elements of one dimension array..Now I am going to consider two dimension array..I'll declare two dimension array as "number2" and print the elements using "Arrays.deepToString()" keyword.Before using that You will have to import 'java.util.Arrays' library.

 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));
      }
}

consider the output,

enter image description here

At the same time , Using two for loops ,2D elements can be printed..Thank you !

if you are running 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);

output:

[7,3,5,1,3]

If using Commons.Lang library, we could do:

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);

Output:

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

If you want to print, evaluate Array content like that you can use Arrays.toString

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

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

jshell> 
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top