简体   繁体   English

在构造函数中创建具有数组特征的数据结构

[英]Create a data structure with the features of an array in the constructor

I want to create a special list data structure that works like an array, in that it's like a list with values x[0], x[1], ... Any advice would be much appreciated. 我想创建一个像数组一样工作的特殊列表数据结构,因为它就像一个值x [0],x [1],...的列表。任何建议都将不胜感激。

I know all of my code isn't perfect I just want to figure out how to fix the one problem I've outlined below. 我知道我所有的代码都不完美,我只想弄清楚如何解决我在下面概述的一个问题。 This is some of the code I have: 这是我的一些代码:

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);
}

However I get the error 'array required, but SpecialList found' when I try to do stuff with y[i] like with System.out.println(y[0]); 但是,当我尝试使用y[i]类似System.out.println(y[0]);操作时,出现错误“需要数组,但找到SpecialList” System.out.println(y[0]); line of code. 代码行。

' lengthList ' works but getting the individual values of y[i] , the list doesn't. ' lengthList '有效,但获取y[i]的单个值,列表不起作用。 I cant work out whats wrong with my constructor for it to not work how I want it to. 我无法解决我的构造函数出了什么问题,因为它无法按我的意愿工作。

You can't redefine what [n] means based on what object it's applied to; 您无法根据其应用于的对象来重新定义[n]含义; that's an array-specific notation. 这是特定数组的符号。 So y[0] where y is a SpecialList instance just won't work. 所以y[0]其中ySpecialList实例将不起作用。 If it could work, List (or at least ArrayList or other implementions where direct addressing is cheap) would probably have that feature. 如果可行, List (或至少ArrayList或直接寻址便宜的其他实现)可能具有该功能。

Although you can do that in some other languages, you can't in Java. 尽管您可以使用其他一些语言来做到这一点,但是您不能使用Java。 It's just not a feature Java offers. 它不是Java提供的功能。 (Which is a good thing or a bad thing depending on your point of view...) Instead, you'll have to provide get and set methods or similar, just like List does. (根据您的观点,这是好事还是坏事……)相反,您必须像List一样提供getset方法或类似方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM