Basic java sorting: arrays and java sorting Arrays
Create an array
You can create an array in the following ways:
1 int[] a;2 int[] b = new int[5];3 String c[] = new String[] { "Hello", "World" };4 double [] d = new double[6];
We are used to the second method. The first method is to declare that the array is not initialized. When using this method, errors are often reported because we forget to initialize the variable. The third and fourth types are just a matter of writing habits.
For array initialization, the default value of the numeric type is 0, the default value of the string type is null, and the default value of the boolean type is false. Java also provides a simple method. For this method, the size of the array is the number of initialization values. Note that the size of an array cannot be changed once it is created, but the value of an array element can be changed.
int[] numbers={2005,1007,1994,2015};
When the return value is used, we can directly create an anonymous array without creating a variable.
1 public String[] getSomethings(String input) {2 //TODO: do something ...3 return new String[]{input};4 }Access to array elements
The elements in the array are accessed through the element index.
int[] numbers = { 2005, 1007, 1994, 2015 }; System.out.println(numbers[1]);
Once the subscript accessed exceeds the index of the array, an exception occurs when the index of the array exceeds the boundary. Therefore, you must pay attention to this when using the array.
We usually use for to facilitate the elements in an array, which facilitates the control of each element in the array.
int[] numbers = { 2005, 1007, 1994, 2015 }; for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); }
You can also use the foreach method.
Common basic functions of Arrays
Array Operations are generally performed in the java. util. Arrays class.
1. output the array as a string
1 int[] numbers = { 2005, 1007, 1994, 2015 };2 String input = Arrays.toString(numbers);3 System.out.println(input);
2. Copy an array
Int [] numbers = {2005,100 7, 1994,201 5}; int [] tempNumbers = numbers; // copy the array reference System. out. println (Arrays. toString (tempNumbers); numbers [0] = 1999; System. out. println (tempNumbers [0]);
To directly copy the values of all elements in the array, use the Arrays. copyOf method.
Int [] numbers = {2005,100 7, 1994,201 5}; int [] tempNumbers = Arrays. copyOf (numbers, 6); // for redundant elements, 0 is assigned to the System. out. println (Arrays. toString (tempNumbers ));
You can also use the System. arraycopy Method
int[] numbers = { 2005, 1007, 1994, 2015 }; int[] tempNumbers=new int[5]; System.arraycopy(numbers, 0, tempNumbers, 1, numbers.length); System.out.println(Arrays.toString(tempNumbers)); numbers[0]=2000; System.out.println(tempNumbers[0]);
3. array sorting
int[] numbers = { 2005, 1007, 1994, 2015 }; Arrays.sort(numbers); System.out.println(Arrays.toString(numbers));