2015-11-12 164 views
3

我已经给出了一个挑战,即我必须从给定的索引处获得列表项的值,这是Queue类(项目是私有的)之外的。我不允许修改这个类,也不允许使用Reflection。是否有可能(在真实情况下,我宁愿创建公共访问器来获取项目值)?访问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; 
    } 
} 

回答

5

您可以:

  1. Queue删除所有的元素,运用shift
  2. 每个移除的元素在ArrayList添加到您自己ArrayList
  3. 迭代,并重新添加元素到Queue使用push以相同的顺序为了恢复Queue到其原始状态。
  4. 返回您的ArrayListindex'th元素。

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

+0

是的,你是对的。我认为我错过了整数的shift()返回值。 –

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(); 
    } 
+0

你忘了增加索引 – orique