Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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);

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);

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.

Add right Maven dependency to your POM:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.3.2</version>
</dependency>

Why don't you do a for loop and store all the elements to one String and then use .split ?

String result = null;
for(String aux : a1){
   final += aux + ";";
}

for(String aux1 : a2){
   final += aux1 + ";";
}
String[] finalArray= result.split(";");

I made this out of the paper, but I'm almost sure it will work ;)

I found that the easiest way to avoid all those startingIndex and endingIndex parameters in arrayCopy() and copyOf() is to write a specific method (which is straightforward):

public static String[] concatTwoStringArrays(String[] s1, String[] s2){
    String[] result = new String[s1.length+s2.length];
    int i;
    for (i=0; i<s1.length; i++)
        result[i] = s1[i];
    int tempIndex =s1.length; 
    for (i=0; i<s2.length; i++)
        result[tempIndex+i] = s2[i];
    return result;
}//concatTwoStringArrays().

So here's the usage of concatTwoStringArrays() method:

String[] s3 = concatTwoStringArrays(s1, s2);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top