简体   繁体   中英

what is the data type that i want to use when merging Array when i merge String array and Integer Array into merge Array

I have an String Array and Integer Array,

String[] strArray={"a","b","c"};
Integer[] intArray={1,2,3};

I want two merge them into another array.What is the data type of merge Array?and how i implement merge Array?

In Java, String and Integer both are inherited from Object. So you can use Object type to define a general array.

    String[] strArray = { "a", "b", "c" };
    Integer[] intArray = { 1, 2, 3 };
    Object[] arr = new Object[strArray.length + intArray.length];
    int j = 0;
    for (int i = 0; i < strArray.length; i++) {
        arr[j++] = strArray[i];
    }
    for (int i = 0; i < intArray.length; i++) {
        arr[j++] = intArray[i];
    }

The first instinct would be to me:

In Java you just can have one Type for container, if you want to mix two types, you have to create some abstraction, like an Interface, or create another way to relate your String with your Integer.

But

consider the @kimdung answer if you just want to mix the two arrays and just this , and if you don't care anything else.

你需要使用对象类型数组,就像在你的情况下你使用整数包装器对象和字符串,它可以合并为java中的对象

Make a Sting array and merge both into that array, you will have to convert Integer to String while merging and the converse when you are retrieving for any purpose

for(int i=0; i<intArray.length; i++) {
     mergerArray[i] = String.value(intArray[i]);
}

You can use System.arraycopy();

String[] strArray={"a","b","c"};
Integer[] intArray={1,2,3};
Object[] objArray = new Object[strArray.length + intArray.length];

System.arraycopy( strArray, 0, objArray, 0, strArray.length );
System.arraycopy( intArray, 0, objArray, strArray.length, intArray.length );

Rather than type Object , you can change to desired type like String .

It is not possible to join two arrays of difference types. But I want to recommend you to use instances java.util.ArrayList instead of array. For example you can join these two different arrays.

ArrayList<Character> strArr= new ArrayList<Character>();
strArr.add(new Character('a'));
strArr.add(new Character('b'));
strArr.add(new Character('c'));
ArrayList<Character> intArr= new ArrayList<Character>();
intArr.add(new Character('1'));
intArr.add(new Character('2'));
intArr.add(new Character('3'));
//merge two arrays
strArr.addAll(intArr);

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