首页 > 解决方案 > 在构造函数中创建具有数组特征的数据结构

问题描述

我想创建一个像数组一样工作的特殊列表数据结构,因为它就像一个具有值 x[0]、x[1] 的列表......任何建议将不胜感激。

我知道我的所有代码都不完美,我只想弄清楚如何解决我在下面概述的一个问题。这是我拥有的一些代码:

public class SpecialList {

int[] specialList;
int lengthList;


public SpecialList(int x[]) {
    this.lengthList = x.length;
    this.specialList = new int[lengthList];
    this.specialList = x;
    for (int i=0; i<lengthList; i++) {
        this.specialList[i] = x[i];
    }
}

public SpecialList(SpecialList w) { 
    this.specialList = w.specialList;
}

public SpecialList doSomething(SpecialList y) { 
    int len = y.lengthList;
    //The line below is an example to show the error I get
    System.out.println(y[0]);
    //Do some other stuff to the list y
    return y;
}

//I test the code with this
public static void main(String[] args) {
    SpecialList y = new SpecialList(new int[] {14, 17, 30});
    SpecialList z = x.doSomething(y);
}

但是,当我尝试使用y[i]类似System.out.println(y[0]);代码行的东西时,我收到错误“需要数组,但找到了 SpecialList”。

' lengthList' 有效,但获取 的单个值y[i],列表无效。我无法弄清楚我的构造函数出了什么问题,因为它不能按我想要的方式工作。

标签: javaarraysconstructor

解决方案


您无法[n]根据所应用的对象重新定义含义;这是一个特定于数组的符号。所以一个实例y[0]在哪里是行不通的。如果它可以工作,(或至少或直接寻址便宜的其他实现)可能会具有该功能。ySpecialListListArrayList

虽然你可以用其他一些语言做到这一点,但你不能用 Java。这不是 Java 提供的功能。(根据您的观点,这是好事还是坏事......)相反,您必须提供getset方法或类似的东西,就像这样List做一样。


推荐阅读