BAEL-7453 - Convert byte[] to Byte[] and Vice Versa in Java

This commit is contained in:
ICKostiantyn.Ivanov 2024-01-17 11:14:14 +01:00
parent fe5fd5004c
commit b1df562162
2 changed files with 87 additions and 0 deletions

View File

@ -0,0 +1,38 @@
package com.baeldung.array.conversions;
import org.apache.commons.lang3.ArrayUtils;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
class ByteArrayToPrimitiveByteArrayUnitTest {
public static byte[] expectedArrayValues = {65, 66, 67, 68};
public static Byte[] byteArray = {65, 66, 67, 68};
@Test
void givenByteArray_whenConvertingUsingByteValue_thenGiveExpectedResult() {
byte[] newByteArray = new byte[byteArray.length];
for (int i = 0; i < byteArray.length; i++) {
newByteArray[i] = byteArray[i].byteValue();
}
Assertions.assertThat(newByteArray)
.containsExactly(expectedArrayValues);
}
@Test
void givenByteArray_whenConvertingUsingUnboxing_thenGiveExpectedResult() {
byte[] newByteArray = new byte[byteArray.length];
for (int i = 0; i < byteArray.length; i++) {
newByteArray[i] = byteArray[i];
}
Assertions.assertThat(newByteArray)
.containsExactly(expectedArrayValues);
}
@Test
void givenByteArray_whenConvertingArrayUtils_thenGiveExpectedResult() {
byte[] newByteArray = ArrayUtils.toPrimitive(byteArray);
Assertions.assertThat(newByteArray)
.containsExactly(expectedArrayValues);
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.array.conversions;
import java.util.Arrays;
import org.apache.commons.lang3.ArrayUtils;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
class PrimitiveByteArrayToByteArrayUnitTest {
public static byte[] primitiveByteArray = {65, 66, 67, 68};
public static Byte[] expectedArrayValues = {65, 66, 67, 68};
@Test
void givenPrimitiveByteArray_whenConvertingUsingByteValueOf_thenGiveExpectedResult() {
Byte[] newByteArray = new Byte[primitiveByteArray.length];
for (int i = 0; i < primitiveByteArray.length; i++) {
newByteArray[i] = Byte.valueOf(primitiveByteArray[i]);
}
Assertions.assertThat(newByteArray)
.containsExactly(expectedArrayValues);
}
@Test
void givenPrimitiveByteArray_whenConvertingUsingAutoboxing_thenGiveExpectedResult() {
Byte[] newByteArray = new Byte[primitiveByteArray.length];
for (int i = 0; i < primitiveByteArray.length; i++) {
newByteArray[i] = primitiveByteArray[i];
}
Assertions.assertThat(newByteArray)
.containsExactly(expectedArrayValues);
}
@Test
void givenPrimitiveByteArray_whenConvertingUsingAutoboxingAndArraysSetAll_thenGiveExpectedResult() {
Byte[] newByteArray = new Byte[primitiveByteArray.length];
Arrays.setAll(newByteArray, n -> primitiveByteArray[n]);
Assertions.assertThat(newByteArray)
.containsExactly(expectedArrayValues);
}
@Test
void givenPrimitiveByteArray_whenConvertingUsingArrayUtils_thenGiveExpectedResult() {
Byte[] newByteArray = ArrayUtils.toObject(primitiveByteArray);
Assertions.assertThat(newByteArray)
.containsExactly(expectedArrayValues);
}
}