How to concat two string arrays in Java

10,459

Solution 1

It's not enough to import a type. You need to actually provide that type on the classpath when compiling your code.

It seems

can not resolve "import org.apache.commons.lang3.ArrayUtil"

like you haven't provided the jar containing the type above on your classpath.

Solution 2

Alternatevely you can do it this way

    String[] a3 = Arrays.copyOf(a1, a1.length + a2.length);
    System.arraycopy(a2, 0, a3, a1.length, a2.length);

Solution 3

This code should work. Not as pretty as the ArrayUtils.addAll(), but functional. You also can avoid having to import anything and you won't need to ship a 3rd party library for just one function.

String[] both = new String[a1.length + a2.length];
System.arraycopy(a1,0,both,0, a1.length);
System.arraycopy(a2,0,both,a1.length + 1, a2.length);

Solution 4

Download common.codec-1.9.jar (Download zip and extract you will find the jar file) then if you are using an IDE like

Eclipse:

1.Right-click your Project.

2.Select Properties.

3.On the left-hand side click java build path.

4.Under Libraries Tab, click Add External Jars button.

5.Choose the downloaded file and click ok

Netbeans :

1.Right-click your Project.

2.Select Properties.

3.On the left-hand side click Libraries.

4.Under Compile tab - click Add Jar/Folder button.

Solution 5

Add right Maven dependency to your POM:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.3.2</version>
</dependency>
Share:
10,459

Related videos on Youtube

VictorGram
Author by

VictorGram

Updated on September 26, 2022

Comments

  • VictorGram
    VictorGram over 1 year

    I am using JDK 1.7 and Eclipse and trying to concat two string arrays:

    String [] a1 = { "a12", "b12" };
    String [] a2 = { "c12", "d23", "ewe", "fdfsd" };
    

    I have tried

    String[] both = ObjectArrays.concat(a1,a2,String.class); 
    

    imported

    import com.google.common.collect.ObjectArrays;
    

    getting Error:

    can not resolve "import com.google.common.collect.ObjectArrays"
    

    Can anyone help? I am using Maven to build the project.

    • Sotirios Delimanolis
      Sotirios Delimanolis about 10 years
      You want to make a bigger String[] containing the elements of the two other arrays?
    • SCV
      SCV about 10 years
      use ArrayList as typr for both if you dont mind