Java in the basic operation of the array

  In Java, all of the array has a default attribute length for access to the number of elements in an array. 

  1. Array replication: System.arraycopy (). 
  Such as: 
  Str1 int [] = new int [] (1,2,3); 
  Str2 int [] = new int [3]; / / invoked at the same address System.arraycopy (str1, 0, str2, 0, str1.length); / / Source Group of str1, str1 position of a start , copied to the target array str2, storage location, str2 from the first location, the store is a total length of 3 (also str1.length that can be used). 

  Note: If the target array, or other type of use, when the array of changes, the source array values have changed. 

  2. Array sort: Arrays.sort ().    (In the java.util package) 
  Such as: 
  Int [] num = new int [] (3,1,2); 
  Arrays.sort (num); 
  For (int i = 0; i <num.length; i + +) 
  ( 
  System.out.println (num [i]) / / output 1,2,3, in descending order. 
  ) 
  If participation is the sort of target, the target must be achieved Comparable interface through compareTo method to compare engagement sort element. 
  As follows: 
  Student ss [] [] = (new Student new Student (1, "zhangsan") 
  New Student (2, "lisi") 
  New Student (3, "wangwu") 
  New Student (3, "mybole")); 
  Arrays.sort (ss); 
  For (int i = 0; i <ss.length; i + +) 
  ( 
  System.out.println (ss [i]); 
  ) 
………………………………

  Sclass Student implements Comparable 
  ( 
  Int num; 
  String name; 
  Student (int num, String name) 
  ( 
  This.num = num; 
  This.name = name; 
  ) 
  Public String toString () 
  ( 
  Return "number =" + num +","+" name = "+ name; 
  ) 
  Public int compareTo (Object o) 
  ( 
  Student s = (Student) o; 
  / / Return num> s.num? 1: (num == s.num? 0: -1) / / num according to the rules of the sort object 
  / / The following: If num is equally divided, according to sort name 
  Int result = num> s.num? 1: (num == s.num? 0: -1); 
  If (0 == result) 
  ( 
  Result = name.compareTo (s.name); / / String has achieved the compareTo method 
  ) 
  Return result; 
  ) 
  ) 

  3. Has sort of a certain element of the array View: Arrays.binarySearch (). 
  As indicated above: 
  Arrays.binarySearch int index = (num, 3); / / num by an array of digital 3 Index 
  System.out.println ( "index =" + index); / / output 2 
  System.out.println ( "element =" + num [index]); / / 3 

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Facebook
  • DotNetKicks
  • DZone
  • Netvouz
  • Propeller

Tags: ,

Releated Java Articles

Comments

Leave a Reply