About the problem of expanding Java arrays

Source: Internet
Author: User

This is a Java array instance that inserts a number into a sequential array. It's obvious that direct insertion is not going to work, because the Java array is fixed, invariant is not dynamically expandable, want to insert a number must re-create an array, its length is larger than the original array, and then copy it, the next thing to do is to implement the insertion in the new array. Using the System.arraycopy () method, you can copy an array, or you can use a for loop just like a blogger, more intuitive

Import java.util.*;
public class Insert {
    int[] a={2,9,13,28,30,45,58,60};
 
    Public  void Insert (int m) {
    	int[] b=new int[a.length +1];
    	for (int i=0;i<a.length;i++) {
    		b[i]=a[i];
    	}
    	for (int i=0;i<b.length-1;i++) {
    		if (M>b[a.length-1]) {
    			b[b.length-1]=m
    		}
    		if ((b[i]<m) && (b[i+1]>=m)) {for
    			
    			(int j=i;j<b.length-1;j++) {
    				b[j+1]=a[j];
    			}
    			b[i+1]=m;
    			break;
    		}
    	}
    	  for (int i=0;i<b.length;i++) {
    	       System.out.print (b[i]+ "  ");
    		}
    }
	public static void Main (string[] args) {
		//TODO auto-generated method stub
		Insert p=new Insert ();
		Scanner sc=new Scanner (system.in);
		System.out.print ("Please enter the number to insert:");
		int C=sc.nextint ();
        P.insert (c);
        Sc.close ();
	}


For this example, 1, first to copy a new expansion of the array

2, and then determine whether to insert the number is greater than the maximum number, if directly in the last side of the insertion

3, otherwise, insert into the appropriate position and the number after the insertion position to move back

The focus of this topic is to investigate the expansion of the array and cross-border problems, here is more prone to chaos, I have tried many times to eliminate the bug, we must have patience, for the array to be cautious or inadvertently will be crossed errors.




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.