Java 어레이를 인쇄하는 가장 간단한 방법은 무엇입니까?
가 Java를 덮어쓰지 toString()
'인쇄'가 className
+ '@' + 어레이의 16진수(정의)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]
장장 간간 ?? ??? ????다음은 입력 및 출력 예를 제시하겠습니다.
// 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 이후 어레이 내의 어레이에 또는 를 사용할 수 있습니다.주의: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 ]
항상 먼저 표준 라이브러리를 확인하십시오.
import java.util.Arrays;
그 후, 다음의 조작을 시험해 주세요.
System.out.println(Arrays.toString(array));
또는 어레이에 다른 어레이가 요소로 포함되어 있는 경우:
System.out.println(Arrays.deepToString(array));
을 먼저 확인하라입니다.Arrays.toString( myarray )
어떻게 해야 하는지 보기 위해 내 배열의 종류에 집중하고 있었기 때문이다.나는 그것을 반복하고 싶지 않았다.Eclipse 디버거에서 볼 수 있는 것과 같은 간단한 호출을 원했지만 myarray.toString()은 실행하지 않았습니다.
import java.util.Arrays;
.
.
.
System.out.println( Arrays.toString( myarray ) );
JDK1.8에서는 집약 연산과 람다 식을 사용할 수 있습니다.
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
*/
8을 .join()
String 클래스에서 제공되는 메서드로, 대괄호 없이 어레이 요소를 출력할 수 있습니다.선택한 구분 기호(아래 예에서는 공백 문자)로 구분됩니다.
String[] greeting = {"Hey", "there", "amigo!"};
String delimiter = " ";
String.join(delimiter, greeting)
출력은 "Hey there amigo!"가 될 것이다.
Arrays.toString
@Esko 등 여러 사람이 및 메서드를 사용하여 제공하는 솔루션이 가장 좋습니다.
Java 8 - Stream.collect(joining()), Stream.각각
아래에 제시된 다른 방법 중 몇 가지를 나열하고 조금 개선하려고 시도합니다. 가장 주목할 만한 추가 사항은 오퍼레이터의 사용입니다. 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)
하다
자바 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
존.
브라보!
메리
이씨
밥.
존슨
Java 1.4를 사용하는 경우 대신 다음을 수행할 수 있습니다.
System.out.println(Arrays.asList(array));
(물론 1.5+에서도 동작합니다.)
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+" ");
}
Java에서 어레이를 인쇄하는 다양한 방법:
심플한 방법
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 ]
사용법
String[] array = new String[] { "One", "Two", "Three", "Four" }; System.out.println(Arrays.toString(array));
출력: [1 、 2 、 3 、 4 ]
어레이 인쇄
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.문자열;@1ad086a [[Ljava.lang.문자열;@10385c1, [Ljava.lang]String;@42719c[다섯째, 여섯째, 일곱째, 여덟째]
자원:어레이 액세스
일반 for 루프를 사용하는 것이 배열을 인쇄하는 가장 간단한 방법이라고 생각합니다.다음은 intArray를 기반으로 한 샘플 코드입니다.
for (int i = 0; i < intArray.length; i++) {
System.out.print(intArray[i] + ", ");
}
1, 2, 3, 4, 5 로 출력됩니다.
사용하는 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};
업데이트:
네! 오브젝트 어레이를 사용하기 위해 어레이를 오브젝트 어레이 또는 오브젝트 어레이로 변환하는 것은 비용이 많이 들고 실행이 늦어질 수 있습니다.이것은 자동 박스라고 불리는 자바의 성질에 의해 발생합니다.
따라서 인쇄 목적으로만 사용해서는 안 됩니다.어레이를 파라미터로 하여 원하는 포맷을 출력하는 함수를 만들 수 있습니다.
public void printArray(int [] a){
//write printing code
}
최근에 Vanilla #Java에서 이 글을 접했습니다.글쓰기가 그리 편리하지 않다Arrays.toString(arr);
, 그 후 Importjava.util.Arrays;
항상요.
이것은 결코 영구적인 수정이 아닙니다.디버깅을 간단하게 할 수 있는 해킹입니다.
어레이를 직접 인쇄하면 내부 표현과 해시 코드가 나타납니다.가 '아', '아', '아', '아', '아'를 가지게 되었습니다.Object
parent-type으로 합니다.'해킹'을 건 요?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());
}
"moded"를할 수 .-Xbootclasspath/p:target/classes
.
이 시점에서, 다음의 기능을 이용할 수 있습니다.deepToString(..)
5 이후 5 후toString(..)
수 deepToString(..)
다른 어레이를 포함하는 어레이에 대한 지원을 추가합니다.
저는 이것이 꽤 유용한 해킹이라는 것을 알았습니다.자바어스트링 표현에 문제가 있을 수 있기 때문에 어레이가 매우 클 경우 발생할 수 있는 문제를 이해하고 있습니다. 걸 될 수도 있어요.System.out
★★★PrintWriter
그런 경우에 대비해서요
Java 8에서는 간단합니다.두 가지 키워드가 있습니다.
- "Stream":
Arrays.stream(intArray).forEach
레퍼런스: "Method Reference" :
::println
int[] intArray = new int[] {1, 2, 3, 4, 5}; Arrays.stream(intArray).forEach(System.out::println);
내의 하려면 , 「」를 합니다.print
println
ㅇㅇㅇ.
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));
어레이를 루핑하여 각 항목을 루핑할 수 있습니다.예를 들어 다음과 같습니다.
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);
}
어레이의 타입이 char[]인 경우는, 다른 방법이 있습니다.
char A[] = {'a', 'b', 'c'};
System.out.println(A); // no other arguments
인쇄하다
abc
제가 시도한 간단한 단축키는 다음과 같습니다.
int x[] = {1,2,3};
String printableText = Arrays.toString(x).replaceAll("[\\[\\]]", "").replaceAll(", ", "\n");
System.out.println(printableText);
인쇄됩니다.
1
2
3
이 접근방식에서는 루프가 불필요하며 소규모 어레이에만 최적
org.apache..lang3.orgcompany.mpa3을 합니다.는 optionStringUtils.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);
모든 대답에 추가하려면, JSON문자열로 개체를 인쇄하는 것이 또한 선택이다.
사용 잭슨:
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
System.out.println(ow.writeValueAsString(anyArray));
사용 Gson:
Gson gson = new Gson();
System.out.println(gson.toJson(anyArray));
// 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]
여기는 가능한 인쇄 기능:.
public static void printArray (int [] array){
System.out.print("{ ");
for (int i = 0; i < array.length; i++){
System.out.print("[" + array[i] + "] ");
}
System.out.print("}");
}
예를 들어 주요는 이렇습니다.
public static void main (String [] args){
int [] array = {1, 2, 3, 4};
printArray(array);
}
그 출력{[1][2][3][4]} 것이다.
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);
}
}
}
이것은 byte[]인쇄에 대한 중복으로 표시되어 있다참고:바이트 배열에 대해에는 적합할 수 있는 추가적인 방법이 있다.
만약 ISO-8859-1 chars 포함한 String으로 인쇄할 수 있습니다.
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.
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);
출력:
[7,3,5,1,3]
Java 11을 사용하는 경우
import java.util.Arrays;
public class HelloWorld{
public static void main(String []args){
String[] array = { "John", "Mahta", "Sara" };
System.out.println(Arrays.toString(array).replace(",", "").replace("[", "").replace("]", ""));
}
}
출력:
John Mahta Sara
Java 8의 경우:
Arrays.stream(myArray).forEach(System.out::println);
Commons를 사용하는 경우.Lang Library는 다음과 같은 일을 할 수 있습니다.
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);
출력:
{1,2,3,4,5}
{John,Mary,Bob}
언급URL : https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array
'programing' 카테고리의 다른 글
Vue.js는 2개의 다른 메인 레이아웃 (0) | 2022.08.01 |
---|---|
C에서 어레이 인덱스의 올바른 유형은 무엇입니까? (0) | 2022.08.01 |
Nuxt Js를 사용하여 스크립트 태그에 데이터 속성을 추가하는 방법 (0) | 2022.08.01 |
nuxt.js 미들웨어에서 vuex 스토어 getter를 사용할 수 없습니다. (0) | 2022.08.01 |
this.$refs, this.$140, 이거요.Vue 2 Composition API를 사용한 $route 액세스 (0) | 2022.08.01 |