I get these weird characters when I try to print out a vector element!

前端 未结 4 789
青春惊慌失措
青春惊慌失措 2021-01-21 15:29

I\'m using Netbeans. When I run the program below, I get this as output [I@de6ced! How come?

import java.util.Arrays;
import java.util.Vector;

publ         


        
4条回答
  •  庸人自扰
    2021-01-21 16:20

    I think I have figured out what was happening:

     int[] a = new int[1];
     a[0] = 5;
    

    We now have an array of int.

     Vector a1 = new Vector(Arrays.asList(a));
    

    The problem is in the way you are calling Arrays.asList.

    The signature for asList is "public static List asList(T... a)". It does not apply with T == int because int is not an object type. And it cannot match with T == Integer because the base type of the array a is int not Integer. What is actually happening is that T is binding to int[], and Arrays.aslist(a) is returning a List with one element that is the value of a!!!

    Then you create a Vector from the List and get a Vector with one element ... the original int[] that was assigned to 'a'.

     System.out.println(a1.elementAt(0));
    

    Finally, a1.elementAt(0) fetches the int[], and you end up calling the Object implementation of the toString() method.

    A couple of important lesson to learn from this:

    • it is a bad idea to mix raw types and generic types as you do on the line that declares a1, and
    • it is a bad idea to ignore, or turn off the compiler's generic type-safety warnings

提交回复
热议问题