Common ways to manipulate arrays in Java

Source: Internet
Author: User

1. Declaring an array

1 New String[5];   2 string[] arr2 = {"a", "b", "c", "d", "e"};   3 New string[]{"a", "b", "c", "d", "e"};  

2. Output an array

 1  int  [] arr = {1, 2, 3, 4, 5 };  2  String arrstring = arrays.tostring (arr  );  3  4  //  Direct output, for memory address   5  system.out.println (arr);   6  //  7    System.out.println (arrstring);   9  //  

3. Check if an array contains a value

1 string[] arr= {"a", "b", "c", "d", "e" };   2 Boolean b = arrays.aslist (arr). contains ("a");   3 System.out.println (b);   4 // true  

4. Connect two arrays

1 // using the Apache Commons Lang Library 2 3 int [] arr1 = {1, 2, 3, 4, 5 };   4 int [] arr2= {6, 7, 8, 9, ten };   5 int

 //system.arraycopy () 
1 static string[] concat (string[] a, string[] b) { 2 string[] C = new string[a.length + B.leng th]; 3 system.arraycopy (a, 0, c, 0, a.length); 4 system.arraycopy (b, 0 5 return c; 6 }
 1  //  2  3  public  static  int  [] concat ( Span style= "color: #0000ff;" >int  [] first, int  [] second) { Span style= "color: #008080;" >4  int  [] result = arrays.copyof (first, first.length + second.length);  5  system.arraycopy (second, 0 6  return   result;  7 } 

5. Reverse output an array

1 // Apache Commons Lang Library 2 3 int [] arr= {1, 2, 3, 4, 5 };   4 arrayutils.reverse (intarray);   5 System.out.println (arrays.tostring (intarray));   6 // [5, 4, 3, 2, 1]  
1 int[] arr = {1, 2, 3, 4, 5 };2 int[] Revarr =New int[arr.length];3  for(inti = 0; I < arr.length; i++){4revarr[i] = arr[arr.length-i-1];5 }6 System.out.println (arrays.tostring (revarr));7 8 //[5, 4, 3, 2, 1]

6. Move the elements in the divisor group

1 // Apache Common Lang   2 3 int [] arr= {1, 2, 3, 4, 5 };   4 int [] removed = arrayutils.removeelement (intarray, 3); // Create a new array   5 System.out.println (arrays.tostring (REMOVED))

Common ways to manipulate arrays in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.