Manipulate Java Arrays

Source: Internet
Author: User

Manipulate Java Arrays

If you have done a lot of Java programs, you may be familiar with Java Collection classes, such as vector and arraylist. You can create a set and add elements to it:


   List lst = new ArrayList();

   lst.add(new Integer(37));

In this special example, an integer value 37 is used to construct an integer encapsulation class object, which is then added to the List.

This simple example shows the basics of a set-they are used to manipulate a column of objects, each of which is a class or interface type. Therefore, an arraylist can contain objects of the object, String, float, and runnable types. The Collection class cannot be used for a list of original data types, such as an integer array.

If you use arrays of the original type in your program, how do you manipulate them? This tip shows you some of the technologies you can use.

The first technology is sorting. The Java. util. arrays class contains a set of class methods for sorting and searching arrays. For example:


   import java.util.Arrays;

   public class ArrayDemo1 {
       public static void main(String args[]) {
           int vec[] = {37, 47, 23, -5, 19, 56};
           Arrays.sort(vec);
           for (int i = 0; i < vec.length; i++) {
               System.out.println(vec[i]);
           }
       }
   }

This demo initializes an integer array and then calls arrays. sort to sort the array in ascending order.

Similarly, you can perform a binary search on the sorted array:


   import java.util.Arrays;

   public class ArrayDemo2 {
       public static void main(String args[]) {
           int vec[] = {-5, 19, 23, 37, 47, 56};
           int slot = Arrays.binarySearch(vec, 35);
           slot = -(slot + 1);
           System.out.println("insertion point = " + slot);
       }
   }

This program has a subtle concept. If the binary search fails, it will return:

-(Insertion point)-1

This
The demo program calls the search method with parameter 35, and the parameter does not exist in the array, and the return value of the method is-4. If this value is added and its negative number is obtained, 3 is obtained, this is the bit 35 should be inserted into the array.
In other words, values-5, 19, and 23 are 0, 1, and 2 in the array. Therefore, the value 35 should be at the index 3 position, while the value 37,
47 and 56 are postponed. The search method does not actually insert data, but just specifies where to insert data.

In addition to sorting and searching, what can we do for the original array? Another useful technique is to convert an original array to an equivalent array of object types. Each corresponding element uses their encapsulate class. For example, in an encapsulated array, 37 becomes INTEGER (37 ).


   import java.util.Arrays;
   import java.lang.reflect.Array;
   
   public class ArrayDemo3 {
   
       // if input is a single-dimension primitive array,
       // return a new array consisting of wrapped elements,
       // else just return input argument
   
       public static Object toArray(Object vec) {
   
           // if null, return
   
           if (vec == null) {
               return vec;
           }
   
           // if not an array or elements not primitive, return
   
           Class cls = vec.getClass();
           if (!cls.isArray()) {
               return vec;
           }
           if (!cls.getComponentType().isPrimitive()) {
               return vec;
           }
   
           // get array length and create Object output array
   
           int length = Array.getLength(vec);
           Object newvec[] = new Object[length];
   
           // wrap and copy elements
   
           for (int i = 0; i < length; i++) {
               newvec[i] = Array.get(vec, i);
           }
   
           return newvec;
       }
   
       public static void main(String args[]) {
   
           // create a primitive array
   
           int vec[] = new int[]{1, 2, 3};
   
           // wrap it
   
           Object wrappedvec[] = (Object[])toArray(vec);
   
           // display result
   
           for (int i = 0; i < wrappedvec.length; i++) {
               System.out.println(wrappedvec[i]);
           }
       }
   }

The "toarray" parameter of the method is an object (arrays can be assigned to an object for reference ). If the parameter is null or does not represent an array of the original type, this method simply returns the parameter value. The Java. Lang. Class tool class is used to determine whether a parameter is an array and obtain the type of underlying elements of the array.

After these checks, you can use the reflection tool method of the Java. Lang. Reflect. array tool class to obtain the length of the original array and a single element of the array. Each element obtained by array. Get is returned to the encapsulated class, such as integer or double.

The final example is based on the previous one and shows you how to use the set feature on the array. This assumes that you already have an array of objects.


   import java.util.Arrays;
   import java.util.List;

   public class ArrayDemo4 {
       public static void main(String args[]) {
           Object vec[] = {new Integer(37), new Integer(47)};
           List lst = Arrays.asList(vec);
           lst.set(1, new Integer(57));
           for (int i = 0; i < vec.length; i++) {
               System.out.println(vec[i]);
           }
       }
   }

In this program, VEC is an array of objects, including INTEGER (37) and INTEGER (47), and then
Arrays. aslist is called. It returns a set (list interface type) and uses an array as the background storage of the set. In other words, set types such as arraylist are within it
Has a certain storage type to store collection elements. In this example, the storage type is the array passed to arrays. aslist as a parameter. This means that changes made to the set method will be reflected.
To the underlying array.

Modifying element 1 in the Set also changes the underlying array. The output of the program is:

37
57

Therefore, if you have an object array, you can use the collection feature on it, and the array itself is used as the underlying storage.

We can also convert a set into an array of objects, for example:

Object VEC [] = lst. toarray ();

From: http://www.javaresearch.org/article/showarticle.jsp? Column = 1 & Thread = 2994

Related Article

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.