使用Scanner读取文件整数存入int数组,输出[I@42a57993异常求助
[I@42a57993 When Printing Your Integer Array & How to Fix It Hey there! I totally get why this might feel confusing at first—let's break down exactly what's going on here.
The Root Cause
When you print an array directly with System.out.println(list), you're relying on the default toString() method inherited from the Object class. For arrays, this method doesn't output the actual elements stored inside; instead, it returns a string that tells you two things:
[I: This is a type code meaning "int array" ([denotes an array,Irepresents theintdata type)@42a57993: This is the hexadecimal version of the array's hash code—a unique identifier for the object in memory
That’s precisely why you’re seeing that cryptic [I@42a57993 string instead of your expected integer values.
The Solution: Use Arrays.toString()
As you already figured out, calling System.out.println(Arrays.toString(list)) fixes the issue—and for good reason:
The Arrays.toString() method is purpose-built to convert arrays into human-readable strings. It loops through every element in your int array, converts each value to a string, and formats them into a clean, comma-separated list wrapped in square brackets—exactly what you want when you need to see your array’s contents.
Quick Example to Clarify
Suppose your array holds values [5, 10, 15, 20]:
- Incorrect (default
toString()):System.out.println(myIntArray)→ Outputs[I@42a57993 - Correct (
Arrays.toString()):System.out.println(Arrays.toString(myIntArray))→ Outputs[5, 10, 15, 20]
Just don’t forget to add import java.util.Arrays; at the top of your code file—otherwise, you’ll hit a compile error.
内容的提问来源于stack exchange,提问作者Bodhe

