在 Java 中打印数组

发布于 2024-12-27 20:06:49 字数 359 浏览 3 评论 0原文

我正在编写一个方法来打印它传递的每个对象。通过调用对象的 Object.toString() 方法可以正常工作,但不适用于数组。我可以使用 Object.getClass().isArray() 方法找出它是否是一个数组,但我不知道如何转换它。

int[] a;
Integer[] b;

Object aObject = a;
Object bObject = b;

// this wouldn't work
System.out.println(Arrays.toString(aObject));
System.out.println(Arrays.toString(bObject));

I'm writing a method that prints every Object it get passed. This works fine by calling the Object.toString() method for the object but doesn't works for arrays. I can find out whether it is an Array with the Object.getClass().isArray() method, but I don't know how to cast it.

int[] a;
Integer[] b;

Object aObject = a;
Object bObject = b;

// this wouldn't work
System.out.println(Arrays.toString(aObject));
System.out.println(Arrays.toString(bObject));

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

等往事风中吹 2025-01-03 20:06:49

如果您不知道类型,可以将对象强制转换为 Object[] 并像这样打印它(在确保它确实是一个数组并且可以强制转换为 Object[]< /代码>)。如果它不是 Object[] 的实例,则首先使用 reflection 创建一个 Object[] ,然后打印:

private void printAnyArray(Object aObject) {
    if (aObject.getClass().isArray()) {
        if (aObject instanceof Object[]) // can we cast to Object[]
            System.out.println(Arrays.toString((Object[]) aObject));
        else {  // we can't cast to Object[] - case of primitive arrays
            int length = Array.getLength(aObject);
            Object[] objArr = new Object[length];
            for (int i=0; i<length; i++)
                objArr[i] =  Array.get(aObject, i);
            System.out.println(Arrays.toString(objArr));
        }
    }
}

TESTING:

printAnyArray(new int[]{1, 4, 9, 16, 25});
printAnyArray(new String[]{"foo", "bar", "baz"});

输出:

[1, 4, 9, 16, 25]
[foo, bar, baz]

If you don't know the type you can cast the object to Object[] and print it like this (after making sure it is indeed an array and can be cast to Object[]). If it is not an instance of Object[] then use reflection to create an Object[] first and then print:

private void printAnyArray(Object aObject) {
    if (aObject.getClass().isArray()) {
        if (aObject instanceof Object[]) // can we cast to Object[]
            System.out.println(Arrays.toString((Object[]) aObject));
        else {  // we can't cast to Object[] - case of primitive arrays
            int length = Array.getLength(aObject);
            Object[] objArr = new Object[length];
            for (int i=0; i<length; i++)
                objArr[i] =  Array.get(aObject, i);
            System.out.println(Arrays.toString(objArr));
        }
    }
}

TESTING:

printAnyArray(new int[]{1, 4, 9, 16, 25});
printAnyArray(new String[]{"foo", "bar", "baz"});

OUTPUT:

[1, 4, 9, 16, 25]
[foo, bar, baz]
云巢 2025-01-03 20:06:49

如果您问如何在任何数组上以编程方式调用此方法,那么对于原始数组来说这是不可能的。查看 Arrays 类,您会看到每个基本数组类型都有一个 toString() 重载。

这是因为 int[] 扩展了 Object 而不是 Object[]

编辑:这是一个包含原始数组的冗长解决方案,令人遗憾:

public static void printObject(Object obj) {

    String output;

    if (obj == null) {
        output = "null";
    }
    else if (obj.getClass().isArray()) {

        if (obj instanceof Object[]) {
            output = Arrays.toString((Object[])obj); //Object[] overload
        }
        else if (obj instanceof int[]) {
            output = Arrays.toString((int[])obj);    //int[] overload
        }
        //and so on for every primitive type
    }
    else {
        output = obj.toString();
    }

    System.out.println(output);
}

我希望其他人可以提供更优雅的解决方案,但基于原始数组的限制,这可能是您能做的最好的解决方案。

If you're asking how you can call this method programmatically on any array, it's not going to be possible with primitive arrays. Looking at the docs for the Arrays class, you'll see there's an overload of toString() for every primitive array type.

This is because int[] for example extends Object rather than Object[].

EDIT: here's a regrettably longwinded solution to include primitive arrays:

public static void printObject(Object obj) {

    String output;

    if (obj == null) {
        output = "null";
    }
    else if (obj.getClass().isArray()) {

        if (obj instanceof Object[]) {
            output = Arrays.toString((Object[])obj); //Object[] overload
        }
        else if (obj instanceof int[]) {
            output = Arrays.toString((int[])obj);    //int[] overload
        }
        //and so on for every primitive type
    }
    else {
        output = obj.toString();
    }

    System.out.println(output);
}

I'm hoping someone else can provide a more elegant solution, but based on the limitations of primitive arrays, this might be the best you can do.

今天小雨转甜 2025-01-03 20:06:49

为什么不让 方法重载 解决您的问题?只需编写两个(或多个)具有相同名称但不同签名的方法,然后让编译器决定程序执行时将调用哪个方法:

void print(Object object) {
   System.out.println("Object: " + object);
}

void print(Object[] array) {
    System.out.println("Object[]: " Arrays.toString(array)); 
}

void print(int[] array) {
    System.out.println("int[]: " Arrays.toString(array)); 
}

代码中其他位置的示例用法:

String first = "test";
print(first);   // prints "Object: test";

String[] second = {"A", "B"};    
print(second);   // prints "Object[]: [A, B]" 

int[] third = {1, 2};
print(third);    // prints "int[]: [1, 2]"

Why don't you let method overloading solve your problem? Simply write two (or more) methods with the same name but different signatures and then let the compiler decide which method will be called when the program executes:

void print(Object object) {
   System.out.println("Object: " + object);
}

void print(Object[] array) {
    System.out.println("Object[]: " Arrays.toString(array)); 
}

void print(int[] array) {
    System.out.println("int[]: " Arrays.toString(array)); 
}

Example usage elsewhere in the code:

String first = "test";
print(first);   // prints "Object: test";

String[] second = {"A", "B"};    
print(second);   // prints "Object[]: [A, B]" 

int[] third = {1, 2};
print(third);    // prints "int[]: [1, 2]"
深海蓝天 2025-01-03 20:06:49

如果您不想依赖对象的类本身来重载对象的 toString 方法(以获得比打印类名和哈希码更有用的东西......),则需要使用反射来获取对象的更深层结构

...建议使用一个使用反射来获取更深层次结构的库,例如 GSON:http://code.google.com/p/google-gson/

public static String print(Object object) {
    return new Gson().toJson(object);
}

public static void test() {
    System.out.println(print(new int[][] {new  int[] {1, 2, 3} }));
    // outputs: [[1,2,3]]
    System.out.println(print(new String[] { "aa", "bb", "cc" }));
    // outputs: ["aa","bb","cc"]
}

这可以轻松打印数组,包括多维数组和原始数组。

但真正的好处是,它以统一的方式打印任何类的对象,无论该类是否以任何有用的方式重写了 toString。

You need to use reflection to get to the deeper structure of an Object if you don't want to rely on object's class itself to overload the Object toString method (to get something more useful than printing class name and hash code...)

My suggestion is to use a library that uses reflection to get to the deeper structure, such as GSON: http://code.google.com/p/google-gson/

public static String print(Object object) {
    return new Gson().toJson(object);
}

public static void test() {
    System.out.println(print(new int[][] {new  int[] {1, 2, 3} }));
    // outputs: [[1,2,3]]
    System.out.println(print(new String[] { "aa", "bb", "cc" }));
    // outputs: ["aa","bb","cc"]
}

This prints arrays effortlessly, including multi-dimensional arrays and primitive arrays.

But the real benefit is that it prints objects of any class in a uniform way, whether the class has overriden toString in any useful way or not.

—━☆沉默づ 2025-01-03 20:06:49

如果您只想将其作为字符串打印出来,为什么要强制转换它呢?只需将其视为对象数组,迭代该数组,然后调用每个对象的 toString() 方法即可。

If all you want to do is print it out as a String, why cast it? Just treat it as an array of Objects, iterate through the array, and the call the toString() method on each Object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文