search
HomeJavajavaTutorialSummary of common operations on arrays based on java (collection)

The following editor will bring you a summary of common operations of Java basicsArray(a must-read article). The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.

Commonly used operations on arrays

1. Find the value in an array Maximum value, minimum value

Idea:Assume that the element with subscript 0 is the maximum value,Traverse the array , compare it with max in turn. If there is an element larger than this max, assign this value to max. The minimum value is the same

public class TestArray{
  public static void main(String[] args){
    int[] arr={23,45,234,576,34,87,34,12,67};
    int max=arr[0];
    int min=arr[0];
    for(int i=0;i<arr.length;i++){
      if(arr[i]>max){
        max=arr[i];
      }
      if(arr[i]<min){
        min=arr[i];
      }
    }
    System.out.println("数组中最大值为:"+max);
    System.out.println("数组中最小值为:"+min);
  }
}

2. Find whether an element exists in the array

import java.util.Scanner;
public class TestArray{
  public static void main(String[] args){
    Scanner in=new Scanner(System.in);
    int[] arr={23,45,234,576,34,87,34,12,67};
    System.out.println("请输入你要查找的元素");
    int element=in.nextInt();
    int i,flag=0;
    for(i=0;i<arr.length;i++){
      if(arr[i]==element){
        flag=1;
        break;
      }
    }
    if(flag==1){
      System.out.println("你要查找的元素的下标为:"+i);
    }else{
      System.out.println("你要查找的元素不存在");
    }
  }
}

(2), use Binary searchmethod to find whether an element exists in an array

Premise: The array to be searched must be ordered (size in order)

Principle: Put the array to be searched The element is compared with the middle subscript element in the array. If it is greater than the middle element, search to the right; if it is smaller than the middle element, search to the left.

public static int binarySearch(int[] arr,int ele){
    int left=0;
    int right=arr.length-1;
    int mid;
    int index=-1;
    while(left<=right){
      mid=(left+right)/2;
      if(arr[mid]==ele){
        index=mid;
        break;
      }else if(arr[mid]<ele){
        left=mid+1;
      }else if(arr[mid]>ele){
        right=mid-1;
      }
    }
    return index;
  }

3. Sort the array

##(1)、Bubble sort

Principle: Compare adjacent elements, small ones move forward, big ones move backward, and the maximum value appears at the largest

index

Analysis: Compare for the first time, the larger one will appear later, and the maximum value will be ranked at the largest index

Compare for the second time, because the maximum value has been determined, only the first n-1 need to be compared Elements are enough, determine the second largest value and rank it at the second largest index

Determine the third largest value and the fourth largest value in turn.............

Conclusion: N numbers are queued up, and the smaller ones are at the front. The outer loop is n-1, and the inner loop is n-1-i


public class TestArray{
  public static void main(String[] args){
    int[] arr={10,3,8,1,6};
    //外层循环控制比较轮数
    for(int i=0;i<arr.length-1;i++){
      //内层循环控制每轮比较次数
      for(int j=0;j<arr.length-1-i;j++){
        if(arr[j]>arr[j+1]){
          int temp=arr[j];
          arr[j]=arr[j+1];
          arr[j+1]=temp;
        }
      }
    }
    //遍历数组
    for(int i=0;i<arr.length;i++){
      System.out.println(arr[i]);
    }
  }
}

(2)、Select sort

Principle: Starting from subscript 0, compare with the following elements in sequence. If the following elements are less than the element with subscript 0, transpose. Compare the new element with index 0 to the following element. The first time is completed, the minimum value appears at index 0

Example: {10, 3, 8, 1, 6}

The first round of comparison starts from the 0 subscript element, in sequence To compare with the following elements, first compare 10 and 3, 101, transpose

{1, 10, 8, 3, 6}, then compare 1 and 6, 1The second round of comparison, the previous round has determined that the element with subscript 0 is the minimum value, this round of comparison starts from subscript 1 , first compare 10 and 8, transpose {1, 8, 10, 3, 6}; compare 8 and 3, transpose {1, 3, 10, 8, 6}, compare 3 and 6, do not transpose. At the end of the second round, it is determined that the penultimate element is at subscript 1.

..........

Compare length-1 round in total.

##

public class TestArray{
  public static void main(String[] args){
    int[] arr={10,3,8,1,6};
    for(int i=0;i<arr.length-1;i++){
      for(int j=i+1;j<arr.length;j++){
        if(arr[i]>arr[j]){
          int temp=arr[i];
          arr[i]=arr[j];
          arr[j]=temp;
        }
      }
    }
    //遍历数组
    for(int i=0;i<arr.length;i++){
      System.out.println(arr[i]);
    }
  }
}

4, Delete elements in the array

(1) Delete elements according to subscripts (fill in gaps with 0)

public static void delete(int[] arr,int index){
    for(int i=index;i<arr.length-1;i++){
      arr[i]=arr[i+1];
    }
    arr[arr.length-1]=0;
    System.out.println(Arrays.toString(arr));
  }

(2) Delete the corresponding elements in the array according to the input elements

public static void delete(int[] arr,int ele){
    int index=-1;
    for(int i=0;i<arr.length;i++){
      if(arr[i]==ele){
        index=i;
      }
    }
    for(int i=index;i<arr.length-1;i++){
      arr[i]=arr[i+1];
    }
    arr[arr.length-1]=0;
    System.out.println(Arrays.toString(arr));
  }

Here are some APIs Common operations on arraysIn java, except for the classes and

interfaces under the java.

lang package, you can directly Except for use, classes or interfaces under other packages require the leading package when used. java.util.Arrays class: This class contains various methods for manipulating arrays (such as sorting and searching

).

These are static

methods, which can be used directly by class name and method name. Here we take int array as an example

1、对数组进行快速排序

Arrays.sort(int[] arr);对传入的数组默认进行升序排序

2、返回指定数组内容的字符串表现形式。

Arrays.toString(int[] arr);

3、使用二分法搜索制定数组中的某个元素的下标

Arrays.binarySearch(int[] arr);

4、将将指定的 int 值分配给指定 int 型数组的每个元素。

Arrays.fill(int[] arr,int val);

5、复制指定的数组,截取或用 0 填充(如有必要),以使副本具有指定的长度。

Arrays.copyOf(int[] arr,int newLength);它的返回值是一个数组

6、将指定数组的指定范围复制到一个新数组。 包含起始位置但不包含结束位置。

Arrays.copyOfRange(int[] arr,int from,int to);它的返回值是一个数组

 

其他数组知识:

1、命令行参数:可以在执行java命令时为main方法传入参数值。

用法:运行java命令时传入命令行参数: java 类名 "值1" "值2"...

public static void main(String[] args){},我们可以看到main方法是一个有参的方法,参数是一个字符串数组,在命令行为main方法传值时,传入的值都保存在args字符数组里。

注意:多个参数值之间用空格分割。参数的值将会保存到字符串数组传入main方法,下标从零开始。

在获取命令行参数时需要注意下标不能越界,最大下标应该为参数的个数-1


public static void main(String[] args){
     for(int i=0;i<args.length;i++){
         System.out.println(args[i]);
     }
 }

2、可变参数

可变参数是java1.5之后的新特性,可以代表零到多个相同数据类型变量,是为了解决因参数个数的变化而导致过多的方法重载问题。

注意:

1、可变参数只能用于形式参数(方法定义时),可以把可变参数当作数组来处理。

2、一个方法在最多只能有一个可变参数,可变参数必须作为最后一个参数。

3、调用带可变参数的方法时,数据类型必须与可变参数的类型对应。


public class Test1 {
  public static void main(String[] args){
    double sum=add(4,2.1,3.4,1.2);
    System.out.println(sum);
  }
  public static double add(int a,double...b){
    double sum=a;
    for(int i=0;i<b.length;i++){
      sum+=b[i];
    }
    return sum;
  }
}

例题:

合并数组操作:现有如下一个数组:   int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5}   要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为: int newArr [] ={1,3,4,5,6,6,5,4,7,6,7,5} 

思路: 确定出不为0的个数,这样可以开辟新数组;从旧的数组之中,取出内容,并将其赋给新开辟的数组。


public class Test1 {
  public static void main(String[] args){
    int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5};
    int[] arr=mergeArrays(oldArr);
    System.out.println(Arrays.toString(arr));
  }
  public static int[] mergeArrays(int[] oldArr){
    int count=0;
    for(int i=0;i<oldArr.length;i++){
      if(oldArr[i]!=0){
        count++;
      }
    }
    int[] newArr=new int[count];
    int index=0;
    for(int i=0;i<oldArr.length;i++){
      if(oldArr[i]!=0){
        newArr[index]=oldArr[i];
        index++;
      }
    }
    return newArr;
  }
}

2、使用二分法查找有序数组中元素。找到返回索引,不存在输出-1。使用递归实现


public class Test1 {
  public static void main(String[] args){
    int[] arr={1,2,3,4,5,6,7,8};
    int index=binarySearch(arr,6,0,arr.length-1);
    System.out.println(index);
  }
  public static int binarySearch(int[] arr,int ele,int left,int right){
    int mid=(left+right)/2;
    if(arr[mid]==ele){
      return mid;
    }else if(arr[mid]<ele){
      return binarySearch(arr,ele,mid+1,right);
    }else if(arr[mid]>ele){
      return binarySearch(arr,ele,left,mid-1);
    }
    return -1;
  }
}

The above is the detailed content of Summary of common operations on arrays based on java (collection). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.