-2

i have source code like this

public class Solution {

     private static List<Integer[]> twoSum(int[] numbers, int targets) {
         Map<Integer, Integer> arrayMap = new HashMap<>();
            List<Integer[]> pairList = new ArrayList<>();
            
            for (int i = 0; i < numbers.length; i++) {
                if (arrayMap.containsKey(targets - numbers[i])) {
                    Integer[] temp = { arrayMap.get(targets - numbers[i]), i }; // Put the previous and current index
                    pairList.add(temp);
                }
                else arrayMap.put(numbers[i], i);
            }
            return pairList;
        }
     public static void main(String[] args) {
            // TODO Auto-generated method stub
            int[]nums = {2, 7, 2, 11, 15}; 
            int target=9;
            System.out.println(Arrays.toString(nums));
            List<Integer[]> index =twoSum(nums, target);
            System.out.println(index.toString());
            
        }
}

but i want to run i got error like this

[[Ljava.lang.Integer;@26f0a63f]

how to fix my problem ?

flyingfox
  • 13,414
  • 3
  • 24
  • 39

1 Answers1

2

This isn’t an error message. It’s the result of calling toString on an instance of type List<Integer[]>.

Simply put, array types in Java don’t define a useful toString method. Instead of the array contents, they print the type of the array and its address in memory, hence the "[Ljava.lang.Integer;@26f0a63f". To print an array’s contents, you need to invoke the static helper method Arrays.toString instead. And in your case you will need to do this manually for every item in your List<Integer[]>:

System.out.println("[");
for (final Integer[] nested : index) {
    System.out.printf("  %s,\n", Arrays.toString(nested));
}
System.out.println("]");

An arguably better way of writing this, because it uses the List.toString method, is using the stream API:

final List<String> indexStr = index.stream()
    .map(Arrays::toString)
    .collect(Collectors.toList());
System.out.println(indexStr);

(Note that I’m not calling indexStr.toString() explicitly — passing an object to println does that automatically for me!)

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214