有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我遇到了一个挑战,我必须从队列类外部(项目是私有的)获取给定索引下列表项的值。我不允许修改类,也不允许使用反射。有没有可能(在真实的情况下,我宁愿创建公共访问器来获取项目值)

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) 个答案

  1. # 1 楼答案

    你可以试试这个

    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());      
    }}
    
  2. # 2 楼答案

    以上源代码是队列的基本实现。从你的问题中,我了解到你想要提取给定索引的项。我认为你应该迭代数据以得到更好的索引。如果在找到该索引之前到达数组的末尾,则可以抛出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();
        }
    
  3. # 3 楼答案

    你可以:

    1. 使用shiftQueue中删除所有元素
    2. 将每个删除的元素添加到自己的ArrayList
    3. 迭代ArrayList并使用push以相同的顺序将元素重新添加到Queue,以便将Queue恢复到其原始状态
    4. 返回ArrayList的第index个元素

    这是非常低效的,但它解决了你的挑战