Operations of Java arrays and JAV collection classes

Source: Internet
Author: User
Tags array array length arrays integer interface sort wrapper
Collections | Arrays If you've done a lot of Java programs, you might be familiar with Java collection classes, such as vectors and ArrayList. You can create a collection and add elements to it:

List lst = new ArrayList (); Lst.add (New Integer (37));

In this particular example, an integer value of 37 is used to construct an integer encapsulated class object, and then that object is added to the list.

This simple example shows a foundation for a collection-they are used to manipulate a list of objects, each of which is a class or interface type. Therefore, a ArrayList can contain object,string,float and runnable types of objects. Collection classes cannot be used for lists of raw data types, such as Integer arrays.

If you use an array of primitive types in your program, how do you manipulate them? This technique will show you a few techniques you can use.

The first technique is sorting. The Java.util.Arrays class contains a set of class methods for sorting and finding 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 array of integers and then calls the Arrays.sort ascending sort that array.

Similarly, you can do a binary lookup on an array of sorted sequences:

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 notion that if the binary lookup fails it will return:

-(insertion point)-1

The demo program calls the lookup method with parameter 35. And that parameter does not exist in the array, the method returns a value of 4, and if the value is repeated with its negative number, it gets 3, which is where 35 should be inserted into the array, in other words, the value-5, 19, and 23 occupy the same position in the array as 0,1 and 2. Therefore the value 35 should be in the position of index 3, while 37, 47 and 56 are postponed. The search method does not perform an actual insert operation but simply indicates where it should be inserted.

In addition to sorting and finding, what else can we do with the original type array? Another useful technique is to convert an original array to an equivalent array of object types. Each corresponding element uses their wrapper class, for example, in an encapsulated array, where 37 is an 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 a 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 parameter of the method "ToArray" is an object (an array can be assigned to an object reference). This method simply returns the parameter value if the parameter is null or represents an array of primitive types. The Java.lang.Class tool class is used to determine whether a parameter is an array and to get the type of the underlying element of the array.

Once these checks are done, the reflection tool method using the Java.lang.reflect.Array tool class can get the length of the original array and get the individual elements of the array. Each element obtained by Array.get is returned to the wrapper class, such as Integer or double.

The final example is based on the previous one and shows you how to use the collection attributes 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 (Panax), 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, containing an integer (37) and an integer (47), and then Arrays.aslist is invoked. It returns a collection (the list interface type) that uses an array as the background store for the collection. In other words, a collection type such as ArrayList has a storage type inside it to store the collection elements. In this example, the storage type used is passed as a parameter.



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.