gpt4 book ai didi

java - 从对象本身确定对象在数组中的索引

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:50:41 25 4
gpt4 key购买 nike

有没有办法让数组中的对象检测它们在哪个插槽中?如果我有一个 Object 数组,数组中的 Object 是否可以在没有被明确告知的情况下检测到它所在的单元格?

最佳答案

不,不幸的是,数组在 Java 中的工作方式是数组简单地“指向”一个对象。由于 Java 数组仅存储(对对象的)引用,但任意数量的变量都可以引用同一个对象,因此对象不知道它在数组中的位置。事实上,数组中的多个索引可以指向同一个对象!

考虑

Object o = new Object(); // The variable o has a "reference" to the Object in memory
Object[] arr = new Object[3]; // empty array to hold Object types
arr[0] = o; // the first index points to the Object we created above
arr[1] = o; // the second index points to that same object!
arr[2] = o; // still the same object! If we modified the original object (assuming it's not immutable) in any way, all the indices in this array would point to the modified object.

希望这对您有所帮助!

遍历对象数组的最快(最容易编写)的方法是

for (Object o : arr) {
// do something to the local variable o, which you can think of as representing each object in your array
}

关于java - 从对象本身确定对象在数组中的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15594433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com