如何在Java中查詢兩個陣列的並集?
在Java中,陣列是一個物件。它是一種非原始資料型別,用於儲存相同資料型別的數值。
根據題意,我們需要找到兩個陣列的並集。並集指的是合併在一起,而陣列的並集指的是一個新的陣列,它包含來自輸入陣列的所有唯一元素。
讓我們探討這篇文章,看看如何使用Java程式語言來實現。
展示一些例項
例項1
Suppose the first array is {0, 3, 5, 6, 9, 1}.
And the second array is {1, 2, 6, 10, 8, 7}.
執行並集操作後的結果將是:
Union of two arrays is: [0, 1, 2, 3, 5, 6, 7, 8, 9, 10]
例項2
Suppose the first array is {0, 5, 11, 7, 9, 3}.
And the second array is {1, 2, 4, 5, 12, 7}.
執行並集操作後的結果將是:
Union of two arrays is: [0, 1, 2, 3, 4, 5, 7, 9, 11, 12]
例項3
Suppose the first array is {12, 13, 5, 16, 9, 19}.
And the second array is {16, 2, 60, 9, 8, 5}.
執行並集操作後的結果將是:
Union of two arrays is: [16, 2, 19, 5, 8, 9, 12, 60, 13]
演算法
步驟1 - 宣告並初始化一個整數陣列。
步驟2 - 初始化HashSet來儲存第一個和第二個陣列的並集。
步驟3 - 將第一個陣列和第二個陣列的所有元素新增到集合中。
步驟4 - 列印結果。
語法
要獲取陣列的長度(陣列中的元素個數),陣列有一個內建屬性,即length。
以下是它的語法:
array.length
要將陣列轉換為元素列表,java.util包的Arrays類提供內建的asList()方法。
以下是它的語法:
Arrays.asList(array);
其中,“array”指的是陣列引用。
多種方法
我們提供了不同的方法來解決這個問題。
使用陣列的靜態初始化。
使用使用者自定義方法。
讓我們逐一檢視程式及其輸出。
方法1:使用陣列的靜態初始化
示例
在這種方法中,陣列元素將在程式中初始化。然後,根據演算法查詢兩個陣列的並集。
import java.util.*;
public class Main{
//main method
public static void main(String[] args){
//Declare and initialize the first array elements
Integer arr1[] = {12, 13, 5, 16, 9, 19};
//Declare and initialize the second array elements
Integer arr2[] = {16, 2, 60, 9, 8, 5};
//Initialize Hashset to perform union operation
HashSet<Integer> set = new HashSet<>();
//add first array to set
set.addAll(Arrays.asList(arr1));
//add second array to set
set.addAll(Arrays.asList(arr2));
//convert to array from set
Integer[] union = {};
union = set.toArray(union);
//print the result
System.out.println("Union of two arrays is: " + Arrays.toString(union));
}
}
輸出
Union of two arrays is: [16, 2, 19, 5, 8, 9, 12, 60, 13]
方法2:使用使用者自定義方法
示例
在這種方法中,陣列元素將在程式中初始化。然後,透過將陣列作為引數傳遞給使用者自定義方法,並在方法內部根據演算法查詢兩個陣列的並集。
import java.util.*;
public class Main{
//main method
public static void main(String[] args){
//Declare and initialize the first array elements
Integer arr1[] = { 0, 5, 11, 7, 9, 3};
//Declare and initialize the second array elements
Integer arr2[] = { 1, 2, 4, 5, 12, 7 };
union(arr1, arr2);
}
//user defined method
public static void union(Integer []arr1, Integer []arr2){
//Initialize Hashset to perform union operation
HashSet<Integer> set = new HashSet<>();
//add first array to set
set.addAll(Arrays.asList(arr1));
//add second array to set
set.addAll(Arrays.asList(arr2));
//convert to array from set
Integer[] union = {};
union = set.toArray(union);
//print the result
System.out.println("Union of two arrays is: " + Arrays.toString(union));
}
}
輸出
Union of two arrays is: [0, 1, 2, 3, 4, 5, 7, 9, 11, 12]
在這篇文章中,我們探討了如何在Java中查詢兩個陣列的並集。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP