Satr massivlarini birlashtirish

+2 ovoz
31 marta ko‘rilgan
so‘radi 25 dekabr, 16 Bilmasvoy (735 bal)

Menga 2 ta satr massivini qo`shish kerak. 

String[] bothArray(String[] first, String[] second) {
    return ??;
}

Shuni eng sodda qaysi usulda qilsam bo`ladi?

2 Javoblar

+1 ovoz
javob berdi 25 dekabr, 16 Saidolim (2,915 bal)

Apache Commons yordamida:

String[] both = (String[])ArrayUtils.addAll(first, second);

bu yerdan


2-variant

public static String[] combine(String[] a, String[] b){
    int length = a.length + b.length;
    String[] result = new String[length];
    System.arraycopy(a, 0, result, 0, a.length);
    System.arraycopy(b, 0, result, a.length, b.length);
    return result;
}

manba, misollari bilan


barcha turlar uchun ishlidigan variant. Bu yerda faqat satrlarni emas, obyektlarni ham yig`sa bo`ladi

public <T> T[] concatenate (T[] a, T[] b) {
    int aLen = a.length;
    int bLen = b.length;

    @SuppressWarnings("unchecked")
    T[] c = (T[]) Array.newInstance(a.getClass().getComponentType(), aLen+bLen);
    System.arraycopy(a, 0, c, 0, aLen);
    System.arraycopy(b, 0, c, aLen, bLen);

    return c;
}

manda

Yana bitta variant Java8 uchun, bu yerda Stream va Lyambda ishlatilgan:

import java.util.Arrays;
import java.util.stream.Stream;
// . . .
String[] bothArray(final String[] first, final String[] second)
{
    return Stream.concat(Stream.of(first), Stream.of(second)).toArray(String[]::new);
}

ixchan va tashki kutubxonalarsiz

Manba

0 ovoz
javob berdi 25 dekabr, 16 Baron (811 bal)
tahrirlandi 25 dekabr, 16 Baron
1-usul:
String[] concat(String[] A, String[] B) {
  int aLen = A.length;
  int bLen = B.length;
  String[] C= new String[aLen+bLen];
  System.arraycopy(A, 0, C, 0, aLen);
  System.arraycopy(B, 0, C, aLen, bLen);
  return C;
}

Ikkinchi usul (import org.apache.commons.lang3.ArrayUtils):

String[] both = ArrayUtils.addAll(first, second);
izoh qoldirdi 25 dekabr, 16 Saidolim (2,915 bal)
Foo[] C  - ishlarmikan? String bo`lishi kerak emasmidi?
izoh qoldirdi 25 dekabr, 16 Baron (811 bal)
ishlamidi, :) copy-paste da qolib ketibdi

Assalomu alaykum, yordam.uz saytimizga xush kelibsiz.

Bu saytda o`zingizni qiziqtirgan savollarga javob olishingiz va o`z sohangiz bo`yicha savollarga javob berishingiz mumkin.

Bizning Oilamizga a'zo bo`lganingiz uchun chuqur Minnatdorchilik bildiramiz !!!

Telegram kanal YordamUzRss

...