首頁 >Java >java教程 >Java 中的動態數組

Java 中的動態數組

WBOY
WBOY原創
2024-08-30 15:28:451081瀏覽

Java 中的動態數組意味著根據使用者需求拉伸或縮小數組的大小。當從陣列中刪除一個元素時,陣列大小必須縮小,如果在陣列中新增一個元素,則陣列大小會變長。陣列用於儲存同質元素,意味著一次可以儲存相同類型的元素。

Java 中動態數組的宣告

範例: 我們可以儲存整數、浮點數、雙精確度數、字串、字元、物件等,但一次只能儲存任何特定類型。

開始您的免費軟體開發課程

網頁開發、程式語言、軟體測試及其他

陣列可以用 3 種方式宣告:

1。數組[]

範例:

int Array[]={1,2,4};

2。 [] 陣列

範例:

int[] Array ={1,2,4};

3。 []A

範例:

int []Array ={1,2,4};

數組元素是如何迭代的?

陣列元素使用以下方式迭代:

  • For 循環
  • While 循環
  • 對於每個循環

還有其他替代方法可以讓陣列變得動態嗎?

  • 是的,透過使用 Java 集合,我們可以實現這一點。
  • 對於動態數組,我們可以使用ArrayList類別。
  • 陣列清單的大小可以根據使用者操作自動增加或減少。

集合Arraylist相比普通動態陣列有什麼優點?

  • 根據使用者需求,數組大小可以增加(拉伸)或減少(收縮),但首先在數組中,我們必須透過編寫添加元素、刪除元素等自訂程式碼,將普通數組變成動態數組。
  • Arraylist 內部實作僅涉及陣列概念。

動態數組在 Java 中如何運作?

  • 要將普通數組變成動態數組,我們必須編寫自訂邏輯,用於新增、刪除元素、增加和減少大小和容量等

文法:

class DynamicArray
{
addingElements()
{
//custom logic
}
addingElementsAtIndex(int index, int element)
{
//custom logic
}
removingElements()
{
//custom logic
}
removingElementsAtIndex(int index, int element)
{
//custom logic
}
increasingSize()
{
//custom logic
}
decreasingSize()
{
//custom logic
}
printArrayElements()
{
//custom logic
}
.
.
.
}
  • ArrayList集合中,不需要編寫自訂邏輯。它將提供添加、刪除元素、獲取大小和容量、根據索引獲取元素、根據索引刪除元素等所有自訂方法

文法:

class ArrayListLogic
{
List<Generic Type> list=new ArrayList<Generic Type>();
list.add();
list.remove(index,element);
.
.
.
}

Java 中的動態陣列範例

下面給出了 Java 中動態陣列的範例:

範例#1

將元素新增至陣列並動態增加大小和容量。

代碼:

package com.dynamicarray;
import java.util.Arrays;
public class DynamicArray {
// declaring an array
int myArray[];
// stores the present size of the array
int sizeOfMyArray;
// stores total capacity of an array
int arrayCapacity;
// initializing array, size and capacity
public DynamicArray() {
myArray = new int[2];
sizeOfMyArray = 0;
arrayCapacity = 2;
}
// method for adding elements
public void addElementsToArray(int element) {
// makes the capacity double if all the array elements filled
if (sizeOfMyArray == arrayCapacity) {
increaseCapacity(2);
}
myArray[sizeOfMyArray] = element;
sizeOfMyArray++;
}
// method for adding elements to specific position
public void addElementAtPosition(int position, int value) {
// makes the capacity double if all the array elements filled
if (sizeOfMyArray == arrayCapacity) {
increaseCapacity(2);
}
// shifting array elements
for (int p = sizeOfMyArray - 1; p >= position; p--) {
myArray[p + 1] = myArray[p];
}
// adding the element at specific position
myArray[position] = value;
sizeOfMyArray++;
}
// method for getting the element from specific position
public int getElementAtposition(int position) {
return myArray[position];
}
// method for increasing capacity if all the elements in an array filled
public void increaseCapacity(int minimumCapacity) {
int temp[] = new int[arrayCapacity * minimumCapacity];
for (int p = 0; p < arrayCapacity; p++) {
temp[p] = myArray[p];
}
myArray = temp;
arrayCapacity = arrayCapacity * minimumCapacity;
}
// method for array current size
public int displaySize() {
return sizeOfMyArray;
}
// method for array total capacity
public int displayCapacity() {
return arrayCapacity;
}
// method for display all elements
public void displayArrayElements() {
System.out.println("elements in array are :" + Arrays.toString(myArray));
}
public static void main(String[] args) {
DynamicArray array = new DynamicArray();
System.out.println("===================================================================");
System.out.println("Inital array size " + array.displaySize() + " and initial capacity " + array.displayCapacity());
System.out.println("===================================================================");
// adding elements at index 0 and 1
array.addElementsToArray(10);//line 1
array.addElementsToArray(20);//line 2
System.out.println("Size of myArray =>" + array.displaySize() + " and Capacity :" + array.displayCapacity());
array.addElementsToArray(30); //line 3
System.out.println("Size of myArray =>" + array.displaySize() + " and Capacity :" + array.displayCapacity());
array.displayArrayElements(); //line 4
// adding element at index 1
array.addElementAtPosition(1, 50);
System.out.println("Size of myArray =>" + array.displaySize() + " and Capacity :" + array.displayCapacity());
array.displayArrayElements();
// adding element at index 2
array.addElementAtPosition(2, 60);
System.out.println("Size of myArray =>" + array.displaySize() + " and Capacity :" + array.displayCapacity());
array.displayArrayElements();
}
}

輸出:

Java 中的動態數組

說明:

  • 在第1行和第2行加入了2個元素;之後,我們嘗試在第 3 行新增一個元素,但陣列的初始容量只有 2。
  • 當我們嘗試插入第三個元素時,陣列容量增加到 4(因為我們指定容量=2*初始大小)。
  • 因此,我們也可以加入第 3 個rd 元素。
  • 第 4 行顯示了所有陣列元素。

範例#2

  • 從陣列中刪除元素並動態減少大小和容量。
  • 這個例子是上面例子的延續。

代碼:

package com.dynamicarray;
import java.util.Arrays;
public class DynamicArray {
// declaring an array
int myArray[];
// stores the present size of the array
int sizeOfMyArray;
// stores total capacity of an array
int arrayCapacity;
// initializing array, size and capacity
public DynamicArray() {
myArray = new int[2];
sizeOfMyArray = 0;
arrayCapacity = 2;
}
// method for adding elements
public void addElementsToArray(int element) {
// makes the capacity double if all the array elements filled
if (sizeOfMyArray == arrayCapacity) {
increaseCapacity(2);
}
myArray[sizeOfMyArray] = element;
sizeOfMyArray++;
}
// method for adding elements to specific position
public void addElementAtPosition(int position, int value) {
// makes the capacity double if all the array elements filled
if (sizeOfMyArray == arrayCapacity) {
increaseCapacity(2);
}
// shifting array elements
for (int p = sizeOfMyArray - 1; p >= position; p--) {
myArray[p + 1] = myArray[p];
}
// adding the element at specific position
myArray[position] = value;
sizeOfMyArray++;
}
// method for getting the element from specific position
public int getElementAtposition(int position) {
return myArray[position];
}
// method for removing elements
public void removeAtPosition(int position) {
if (position >= sizeOfMyArray || position < 0) {
System.out.println("Opps!No elements found " + position + " position");
} else {
for (int p = position; p < sizeOfMyArray - 1; p++) {
myArray[p] = myArray[p + 1];
}
myArray[sizeOfMyArray - 1] = 0;
sizeOfMyArray--;
}
}
// method for increasing capacity if all the elements in an array filled
public void increaseCapacity(int minimumCapacity) {
int temp[] = new int[arrayCapacity * minimumCapacity];
for (int p = 0; p < arrayCapacity; p++) {
temp[p] = myArray[p];
}
myArray = temp;
arrayCapacity = arrayCapacity * minimumCapacity;
}
// method for make an array size to initial size
public void makeInitialSize() {
System.out.println("Making an array to initial size");
int temp[] = new int[sizeOfMyArray];
for (int q = 0; q < sizeOfMyArray; q++) {
temp[q] = myArray[q];
}
myArray = temp;
arrayCapacity = myArray.length;
}
// method for array current size
public int displaySize() {
return sizeOfMyArray;
}
// method for array total capacity
public int displayCapacity() {
return arrayCapacity;
}
// method for display all elements
public void displayArrayElements() {
System.out.println("elements in array are :" + Arrays.toString(myArray));
}
public static void main(String[] args) {
DynamicArray array = new DynamicArray();
System.out.println("===================================================================");
System.out.println("Inital array size " + array.sizeOfMyArray + " and initial capacity " + array.arrayCapacity);
System.out.println("===================================================================");
array.addElementsToArray(10);
array.addElementsToArray(20);
array.addElementsToArray(30);
array.addElementsToArray(40);
array.displayArrayElements();
array.removeAtPosition(2);
System.out.println("Size after Remove Operation=>" + array.displaySize() + " and Capacity :"
+ array.displayCapacity());
array.displayArrayElements();
array.removeAtPosition(2);
System.out.println("Size after Remove Operation=>" + array.displaySize() + " and Capacity :"
+ array.displayCapacity());
array.displayArrayElements();
array.removeAtPosition(1);
System.out.println("Size after Remove Operation=>" + array.displaySize() + " and Capacity :"
+ array.displayCapacity());
array.displayArrayElements();
array.removeAtPosition(2);
System.out.println("Size after Remove Operation =>" + array.displaySize() + " and Capacity :"
+ array.displayCapacity());
array.displayArrayElements();
array.removeAtPosition(1);
System.out.println("Size after Remove Operation =>" + array.displaySize() + " and Capacity :"
+ array.displayCapacity());
array.displayArrayElements();
// Make the array to initial size
array.makeInitialSize();
System.out.println(" After trimming Size of myArray =>" + array.displaySize() + " and Capacity :"
+ array.displayCapacity());
array.displayArrayElements();
array.addElementsToArray(-5);
System.out.println("After trimming Size of myArray =>" + array.displaySize() + " and Capacity :"
+ array.displayCapacity());
array.displayArrayElements();
array.addElementsToArray(-6);
System.out.println("After trimming Size of myArray =>" + array.displaySize() + " and Capacity :"
+ array.displayCapacity());
array.displayArrayElements();
}
}

輸出:

Java 中的動態數組

範例#3

使用 ArrayList 的動態陣列。

代碼:

package com.dynamicarray;
import java.util.ArrayList;
import java.util.List;
public class ArrayListDynamic {
public static void main(String[] args) {
List<Integer> list=new ArrayList<Integer>();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
System.out.println("Adding the elements ArrayList =>"+list);
System.out.println("Adding the elements ArrayList size =>"+list.size());
/*Array List capacity formula newCapacity = (oldCapacity * 3/2) + 1*/
list.add(4, 50);
System.out.println("After adding the element at specific index =>"+list+" and size "+list.size());
list.remove(4);
list.remove(3);
System.out.println("After removing the elements =>"+list+" and size "+list.size());
}
}

輸出:

Java 中的動態數組

結論

在普通的動態數組中,實作開發者必須編寫自訂邏輯,而在集合ArrayList中,所有預定義方法都可用,因此無需編寫自訂邏輯。

以上是Java 中的動態數組的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn