John
John

Reputation: 21

How can I combine elements from different arrays in java?

Suppose a={1,2,3} and b={4,5,6} and I want to return an array containing the middle elements of a and b, i.e., {2,5}. I tried to use "merge":

public int[] middleValueArray(int[] a, int[] b) {
 int[] both=merge(a[1],b[1]);
 return both;
}

This does not seem to work. Is there a simple way to approach this? Thanks!

Upvotes: 0

Views: 193

Answers (4)

Nishikant Nipane
Nishikant Nipane

Reputation: 58

More general solution would be to convert it to list and then add list one by one..for example..

 import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;

    public class Main {
       public static void main(String args[]) {
          String a[] = { "A", "E", "I" };
          String b[] = { "O", "U" };
          List list = new ArrayList(Arrays.asList(a));
          list.addAll(Arrays.asList(b));
          Object[] c = list.toArray();
          System.out.println(Arrays.toString(c));
       }
    }

Upvotes: 0

Andremoniy
Andremoniy

Reputation: 34900

More general solution will be:

public int[] middleValueArray(int[] a, int[] b) {
    return new int[]{a[a.length/2], b[b.length/2]};
}

Upvotes: 1

bit-shashank
bit-shashank

Reputation: 921

Use this:-

public int[] middleValueArray(int[] a, int[] b) {
     int[] both={a[1],b[1]};
     return both;
    }

Upvotes: 0

Václav Struhár
Václav Struhár

Reputation: 1769

you can do it like this:

public int[] middleValueArray(int[] a, int[] b) {
 int[] both=new int[]{a[1],b[1]};
 return both;
}

Upvotes: 0

Related Questions