Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array containing another

Tags:

java

arrays

I have an array tab1 that contains some strings and another array that could contains all element of array tab1. how do I can do this to avoid repeating same element of tab1 :

String[] tab1 ={"AF","HB,"ER"} 
String[] tab2 ={"AF","HB,"ER","HO","NF","BB","CD","PO"}

I would like to say : tab2 = {tab1,"HO",...} any idea ?

thanks,

like image 847
lola Avatar asked Nov 05 '22 15:11

lola


2 Answers

You might want to use Arrays.copyOf() to create an array of size tab1.length + 5, which starts with the elements of tab1, and then add [manually] elements of tab2

Simple example:

    String[] tab1 ={"AF","HB","ER"};
    String[] tab2 = Arrays.copyOf(tab1, tab1.length+5);
    tab2[3] = "HO";
    tab2[4] = "NF";
    tab2[5] = "BB";
    tab2[6] = "CD";
    tab2[7] = "PO";
    System.out.println(Arrays.toString(tab2));

[of course if you have the later elements in a third array you can iterate and add them]

like image 78
amit Avatar answered Nov 11 '22 15:11

amit


how do I can do this to avoid repeating same element of tab1

You can Use List, here there will be only one object for for example "AF" with two reference

List<String> a = new ArrayList<String>;
List<String> b = new ArrayList<String>; 
b.addAll(a);
b.add("HO");
like image 26
jmj Avatar answered Nov 11 '22 14:11

jmj