-
Array-Deklaration
String[] aArray = new String[5]; String[] bArray = {"a","b","c", "d", "e"}; String[] cArray = new String[]{"a","b","c","d","e"};
-
Array-Ausgabe in Java
int[] intArray = { 1, 2, 3, 4, 5 }; String intArrayString = Arrays.toString(intArray); // print directly will print reference value System.out.println(intArray); // [I@7150bd4d System.out.println(intArrayString); // [1, 2, 3, 4, 5]
-
Erstellen einer ArrayList aus einem Array
String[] stringArray = { "a", "b", "c", "d", "e" }; ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(stringArray)); System.out.println(arrayList); // [a, b, c, d, e]
-
Überprüfen eines Arrays auf einen bestimmten Wert
String[] stringArray = { "a", "b", "c", "d", "e" }; boolean b = Arrays.asList(stringArray).contains("a"); System.out.println(b); // true
-
Zwei Arrays zusammenführen
int[] intArray = { 1, 2, 3, 4, 5 }; int[] intArray2 = { 6, 7, 8, 9, 10 }; // Apache Commons Lang library int[] combinedIntArray = ArrayUtils.addAll(intArray, intArray2);
-
Deklarieren eines Arrays in einer Zeile
method(new String[]{"a", "b", "c", "d", "e"});
-
Verketten von Array-Elementen zu einem String
// containing the provided list of elements // Apache common lang String j = StringUtils.join(new String[] { "a", "b", "c" }, ", "); System.out.println(j); // a, b, c
-
ArrayList
In Array konvertierenString[] stringArray = { "a", "b", "c", "d", "e" }; ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(stringArray)); String[] stringArr = new String[arrayList.size()]; arrayList.toArray(stringArr); for (String s : stringArr) System.out.println(s);
-
Konvertieren eines Arrays in eine Menge (
Set
)Set<String> set = new HashSet<String>(Arrays.asList(stringArray)); System.out.println(set); //[d, e, b, c, a]
-
Gibt ein Array mit Elementen in umgekehrter Reihenfolge zurück
int[] intArray = { 1, 2, 3, 4, 5 }; ArrayUtils.reverse(intArray); System.out.println(Arrays.toString(intArray)); //[5, 4, 3, 2, 1]
-
Entfernen eines Elements aus einem Array
int[] intArray = { 1, 2, 3, 4, 5 }; int[] removed = ArrayUtils.removeElement(intArray, 3);//create a new array System.out.println(Arrays.toString(removed));
Und noch etwas: Erstellen Sie ein Array eines Typs
byte
basierend auf einem Wert eines Typsint
(ca. Nehmen SieByteBuffer
, wählen Sie 4 Bytes darin aus und geben Sie die Zahlint
8 ein, und konvertieren Sie dann alles (0, 0, 0, 8) in ein Array des Typsbyte
mit dem Aufrufarray()
)byte[] bytes = ByteBuffer.allocate(4).putInt(8).array(); for (byte t : bytes) { System.out.format("0x%x ", t); }
10 häufig verwendete Array-Techniken in Java
Die folgenden 10 Techniken für Arrays in Java werden häufig verwendet. Sie haben den höchsten Rang bei Stack Overflow, einem System von Fragen und Antworten zum Thema Programmierung.
GO TO FULL VERSION