简体   繁体   English

链接java中的对象引用

[英]Linking object references in java

So I'm doing this project in java where an objects a has an array, a. 所以我在java中做这个项目,其中一个对象有一个数组,一个。 Then, you take a part of the array and assign it to another object, s, such that changing values in s changes them in a. 然后,您获取数组的一部分并将其分配给另一个对象s,以便更改s中的值会更改它们。 I'm banging my head over this, I'm just not getting it. 我正在敲打这个,我只是没有得到它。 There is some concept that I'm missing. 我缺少一些概念。

public class IntArray implements IntSequence {

int[] a;

public IntArray(int size) {
    a = new int[size];
}

public int length() {
}

public int get(int index) {
    return a[index];
}

public void set(int index, int value) {
    a[index] = value;
}

public IntSequence subSequence(int index, int size) {
}

public static void main(String[] args) {
    IntSequence a = new IntArray(5);
    a.set(0, 11);
    a.set(1, 22);
    a.set(3, 33);
    // some more values

    IntSequence s = a.subSequence(2, 2);
    s.set(0, 100);
    s.set(1, 200);

    System.out.println(a.get(2)); // prints 100. 

    }
}


public interface IntSequence {
int length();

int get(int index);

void set(int index, int value);

IntSequence subSequence(int index, int size);
}

Could someone give me a nudge in the right direction? 有人能给我一个正确方向的推动吗? Thank you. 谢谢。

There are a number of ways you can do it. 有很多方法可以做到。

I think the simplest way is by creating a new class that is a subsequence. 我认为最简单的方法是创建一个新的类,它是一个子序列。

public class SubSequence implements IntSequence {
    private int[] a;
    private int start;
    private int size;

    public constructor(int[] arr, int start, int size) {
        this.a = arr;
        this.start = start;
        this.size = size;
    }

    public int get (int index){
        return a[start + index];
    }

    public IntSequence subSequence(int start, int size) { 
        return new SubSequence(a, start, size);
    }
    // And so on
}

Another way is by returning an anonymous class. 另一种方法是返回一个匿名类。 You have to make your variables final to access them from the anonymous class. 您必须使变量最终从匿名类访问它们。 This is slightly better because you don't need a constructor, you should just be able to create lists from existing lists by calling the subSequence method. 这稍微好一些,因为您不需要构造函数,您应该只需通过调用subSequence方法从现有列表创建列表。

public IntSequence subSequence(final int start, final int size) {

    return new IntSequence() {
        public int length() {
            return size;
        }
        public int get(index) {
            return a[start + index ]
        }
        ... and so on
    }
}

This code has no error checking, you should add that to make sure you don't reach beyond the array boundaries, 此代码没有错误检查,您应该添加它以确保不会超出数组边界,

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

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