简体   繁体   中英

Object… Object[] and formatting

I have different types of data (it could be String, Integer...). Here is a simple example :

public static void main(String[] args) {
    before("one");
}

public static void before(Object... datas ) {
    go(1, datas);
}

public static void go(Object...params ) {
    System.out.println(MessageFormat.format("{0} is the same as {1}", params));
}

I want this : "1 is the same as one" but got this "1 is the same as [Ljava.lang.Object;@4554617c"

It seems the problem is in my params, I would like an array like this [1, "one"] but instead "one" is encapsulated inside an array. I would like something to "flat". Any ideas ?

Thanks

what you pass to go is actually 1 and and array containing "one", that is why you get that [Ljava.lang.Object;@4554617c" . You could change you method to:

public static void before(Object... datas) {
    Object[] arr = Stream.concat(Stream.of(1), Arrays.stream(datas))
                         .toArray();
    go(arr);
}

from your example the formatted message always contains 2 parameters, so you can simplify it as follows:

public static void main(String[] args) {
    before("one");
}

public static void go(Object...params) {
    System.out.println(MessageFormat.format("{0} is the same as {1}", params));
}

public static void before(Object data) {
    go(1, data);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM