Create an array:
String[] a = new String[5]; String[] b = {“a”,”b”,”c”, “d”, “e”}; String[] c = new String[]{“a”,”b”,”c”,”d”,”e”};
1. Print the array
We often use for loops or some iterators to print out all elements of the array. But we can also change the posture.
int array[] = {1,2,3,4,5}; System.out.println(array); //[I@1234be4e String arrStr = Arrays.toString(array); System.out.println(array); //[1,2,3,4,5];
2. Create ArrayList
String[] array = { “a”, “b”, “c”, “d”, “e” }; ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(array)); System.out.println(arrayList); // [a, b, c, d, e]
3. Check whether it contains a certain value
int array[] = {1,2,3,4,5}; boolean isContain= Arrays.asList(array).contains(5); System.out.println(isContain); // true
4. Connect two arrays
int[] array1 = { 1, 2, 3, 4, 5 }; int[] array2 = { 6, 7, 8, 9, 10 }; // Apache Commons Lang library int[] combinedIntArray = ArrayUtils.addAll(array1, array2);
5. In one line Declare an array
method(new String[]{"a", "b", "c", "d", "e"});
6, invert the array
int[] intArray = { 1, 2, 3, 4, 5 }; // Apache Commons Lang library ArrayUtils.reverse(intArray); System.out.println(Arrays.toString(intArray)); //[5, 4, 3, 2, 1]
7, delete an element
int[] intArray = { 1, 2, 3, 4, 5 }; int[] removed = ArrayUtils.removeElement(intArray, 3);//create a new array System.out.println(Arrays.toString(removed));
8, convert it to set
Set<String> set = new HashSet<String>(Arrays.asList(new String[]{"a", "b", "c", "d", "e"})); System.out.println(set); //[d, e, b, c, a]
9, convert Array Convert List to Array
String[] stringArray = { "a", "b", "c", "d", "e" }; ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(stringArray)); String[] stringArr = new String[arrayList.size()]; arrayList.toArray(stringArr);
10. Compose array elements into a string
// Apache common lang String j = StringUtils.join(new String[] { "a", "b", "c" }, ", "); System.out.println(j); //a, b, c
For more related knowledge, please pay attention tojava basic tutorialcolumn
The above is the detailed content of 10 commonly used methods for java arrays. For more information, please follow other related articles on the PHP Chinese website!