在Java中访问私有成员而不使用公共访问器

3

我面临一个挑战,必须从Queue类外部获取给定索引处的列表项值(items是私有的)。 我不允许修改该类,并且不允许使用Reflection。 是否有可能实现这一点(在实际情况下,我宁愿创建公共访问器来获取items值)?

class Queue {
    private List<Integer> items;

    private Queue() {
        items = new ArrayList<Integer>();
    }

    public static Queue create() {
        return new Queue();
    }

    public void push(int item) {
        items.add(item);
    }

    public int shift() {
        return items.remove(0);
    }

    public boolean isEmpty() {
        return items.size() == 0;
    }
}
3个回答

5
你可以:
  1. 使用 shiftQueue 中删除所有元素
  2. 将每个被删除的元素添加到你自己的 ArrayList
  3. 遍历 ArrayList,并使用 push 按照相同的顺序重新添加元素到 Queue 中,以恢复 Queue 的原始状态。
  4. 返回你的 ArrayList 中的第 index 个元素。
虽然效率很低,但它能解决你的问题。

是的,你说得对。我想我忽略了 shift() 的返回值是整数。 - aries.wandari

0
你可以试试这个
public class TestQueue {
public static void main(String[] args){

    Queue q=  Queue.create();
    q.push(10);
    q.push(20);
    q.push(30);
    q.push(40);
    q.push(50);     
        System.out.println(q.shift());      
}}

0
以上源代码是队列的基本实现。从您的问题中,我了解到您想要提取给定索引的项目。我认为您应该迭代数据以获取所需的索引。如果在找到该索引之前到达数组末尾,则可以抛出ArrayIndexOutOfBoundsException异常。

这里是一个基本实现。

public void dataRetrieve() throws ArrayIndexOutOfBoundsException {
        Queue queue =  Queue.create();
        queue.push(10);
        queue.push(20);
        queue.push(30);
        queue.push(40);
        queue.push(50);

        int indexToRetrieve = 5;

        int index = 0;
        while(!queue.isEmpty()) {
            int value = queue.shift();
            if (index == indexToRetrieve) {
                System.out.println(value);
                return;
            }
            index++;
        }

        throw new ArrayIndexOutOfBoundsException();
    }

你忘记递增“索引(index)”了。 - orique

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接