Java中一个对象可以同时属于数组和数组列表吗?

问题描述 投票:0回答:1

我正在努力编写一个代码示例,其中对象可以同时属于数组和数组列表,并且在数组列表或数组中进行修改会更改对象吗?请参阅示例,其中我期望在更改后从 Array 和 Arraylist 中获得 Monkey,但只有 Array 发生了更改

import java.util.ArrayList;
 
public class ArrArrList {
    public static void main(String[] args)
    {
 
        // Creating an ArrayList of Object type
        ArrayList<Object> arr = new ArrayList<Object>();
        
        String[] strArray = new String[3]; 
        strArray[0] = "one"; 
        strArray[1] = "two"; 
        strArray[2] = "three"; 

        String[] str = strArray;

        // Inserting String value in arrlist
        arr.add(str[0]);
        arr.add(str[1]);
        arr.add(str[2]);

         System.out.print(
            "ArrayList after all insertions: ");
        display(arr); **// Prints one two three**
        
         System.out.print(
            "Array after all insertions: ");

        for (int i = 0; i < 3; i++) {  
            System.out.print(str[i] + " ");  **// Prints one two three**
        }  
        System.out.println();

        strArray[2] = "Monkey";
        //arr.set(2,strArray[2]);

        System.out.print(
            "ArrayList after change: ");
        display(arr); **// Prints one two three**

         System.out.print(
            "Array after change: ");

        for (int i = 0; i < 3; i++) {  
            System.out.print(str[i] + " ");  **// Prints one two Monkey**
        }  
         System.out.println();
    }
 
    // Function to display elements of the ArrayList
    public static void display(ArrayList<Object> arr)
    {
        for (int i = 0; i < arr.size(); i++) {
            System.out.print(arr.get(i) + " ");
        }
        System.out.println();
    }
}
java arrays object arraylist
1个回答
0
投票

是的,这是可能的。当我们说一个数组(引用类型)或数组列表“包含”某个对象时,它实际上意味着它保存对该对象的引用。两个数组或数组列表完全有可能保存对同一对象的引用。

这种效果在您展示的示例中并不明显,因为您无法更改

String
对象 - 它们是不可变的。当您执行
strArray[2] = "Monkey";
时,您正在使数组保存对 different
String
对象的引用。

也就是说,通过与

String
进行比较,您仍然可以证明数组和数组列表包含相同的
==
对象。这会比较它们是否是相同的对象(而不是比较它们是否具有相同的字符)。

ArrayList<Object> arr = new ArrayList<Object>();

String[] strArray = new String[3];
strArray[0] = new String("one");
strArray[1] = "two";
strArray[2] = "three";

String[] str = strArray;

arr.add(str[0]);
arr.add(str[1]);
arr.add(str[2]);

for (int i = 0 ; i < 3 ; i++) {
    System.out.println(arr.get(i) == str[i]);
}
// this prints 3 "true"s.

作为一个更有意义的示例,您可以使用可变类,例如

StringBuilder
。改变
StringBuilder
的一个简单方法是向其添加
append
一些内容。

ArrayList<Object> arr = new ArrayList<>();

StringBuilder[] strArray = new StringBuilder[3];
strArray[0] = new StringBuilder("one");
strArray[1] = new StringBuilder("two");
strArray[2] = new StringBuilder("three");

arr.add(strArray[0]);
arr.add(strArray[1]);
arr.add(strArray[2]);

strArray[2].append("Some additional content");

System.out.println(strArray[2]);
System.out.println(arr.get(2));
// prints two lines of "threeSome additional content"
© www.soinside.com 2019 - 2024. All rights reserved.