You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中Java自定义类数组赋值异常问题咨询

问题:自定义类数组下移元素后相邻下标出现重复值

我是一名自学的新手,正在Android Studio中开发首个应用。在向自定义类数组的下标写入数据时,相邻下标也会被写入相同值。经排查发现问题出在数组元素下移的代码中:我尝试用LeaderboardData[j + 1] = LeaderboardData[j];将下标j的元素移到j+1,以为会复制所有数据,但后续写入下标i时,i和i+1会出现重复条目;而逐个复制类的字段(如UserName、DateTime、Milliseconds)则一切正常。想请教这段错误代码的具体问题是什么?

自定义类代码

class LeaderboardClass
{
    public String DateTime;
    public String UserName;
    public long Milliseconds; //0 denotes not in use
}

数组声明

LeaderboardClass[] LeaderboardData = new LeaderboardClass[LeaderboardEntries];

问题原因

核心在于Java中引用类型的赋值逻辑:

  • LeaderboardClass属于引用类型,数组LeaderboardData里存储的不是对象本身,而是指向对象实例的引用地址。
  • 执行LeaderboardData[j + 1] = LeaderboardData[j];时,只是把j位置的引用地址复制给了j+1位置,这意味着两个数组元素指向同一个对象实例。后续修改下标i对应的对象字段时,i+1位置的引用指向的是同一个对象,所以会显示相同内容。
  • 而逐个复制字段的方式,是给每个数组位置的对象(或新创建的对象)独立赋值字段值,每个数组元素对应的都是不同的对象实例,修改其中一个自然不会影响其他位置。

正确的元素下移实现

如果要实现元素下移且每个位置都是独立的对象,需要先创建新的LeaderboardClass实例,再复制原对象的字段值:

// 创建新的对象实例
LeaderboardClass newEntry = new LeaderboardClass();
// 逐个复制字段值
newEntry.DateTime = LeaderboardData[j].DateTime;
newEntry.UserName = LeaderboardData[j].UserName;
newEntry.Milliseconds = LeaderboardData[j].Milliseconds;
// 将新对象赋值给目标下标
LeaderboardData[j + 1] = newEntry;

也可以给LeaderboardClass添加复制构造方法,简化操作:

class LeaderboardClass {
    public String DateTime;
    public String UserName;
    public long Milliseconds; //0 denotes not in use

    // 复制构造方法,传入已有对象复制字段
    public LeaderboardClass(LeaderboardClass other) {
        this.DateTime = other.DateTime;
        this.UserName = other.UserName;
        this.Milliseconds = other.Milliseconds;
    }
}

使用时只需一行代码:

LeaderboardData[j + 1] = new LeaderboardClass(LeaderboardData[j]);

内容的提问来源于stack exchange,提问作者Andrew Mitchell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 17:35:24