Beginners: how to manipulate Java arrays as needed

Source: Internet
Author: User
Beginners: how to manipulate Java array developers online builder.com.cn as needed: 2008-04-11Author: Zhimu Source: IT expert network this article keywords: Beginner array manipulating Java

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 [] =;
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 [] =;
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:

This demo calls the search method with parameter 35, and the parameter does not exist in the array. the return value of the method is-4. If this value is added and its negative number is obtained, 3 is obtained, that is, 35 should be inserted into the array.
In other words, values-5, 19, and 23 occupy the positions 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 [];
// 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 represents an array not of the original type
Method. 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 [] =;
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). array is used as the background storage of the set. In other words, a collection type such as arraylist has a storage type inside it 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 ();

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.