【问题标题】:In placed reversed using only get methods仅使用 get 方法放置反转
【发布时间】:2017-10-11 06:31:36
【问题描述】:

Edge.java(接口)

public interface Edge {

  /**
   * get the first node of the Edge.
   * @return the first Node.
   */
  public int getFirstNode();

  /**
   * get the second node of the Edge.
   * @return the second Node.
   */
  public int getSecondNode();

}

EdgeImpl.java(实现)

public class EdgeImpl implements Edge {

  private int node1;
  private int node2;


  public EdgeImpl(int node1, int node2) {
    this.node1 = node1;
    this.node2 = node2;
  }

  @Override
  public int getFirstNode() {
    // TODO Auto-generated method stub
    return node1;
  }

  @Override
  public int getSecondNode() {
    // TODO Auto-generated method stub
    return node2;
  }

}

first.java(我需要什么帮助)

import java.util.ArrayList;
import java.util.List;

public class first {

  public static void main(String[] args) {

    List<Edge> graph = new ArrayList<>();
    Edge a = new EdgeImpl(1, 2);
    Edge b = new EdgeImpl(3, 4);
    graph.add(a);
    graph.add(b);


  }
  public static void reverse(List<Edge> graph) {
    int count = 0;
    while(count < graph.size()) {
      int temp1 = graph.get(count).getFirstNode();
      int temp2 = graph.get(count).getSecondNode();
      graph.get(count).getFirstNode() = temp2;
      graph.get(count).getSecondNode() = temp1;
      count = count + 1;
    }
  }

}

Edge 接口只有两个 int 值,我们有两个 getter。

假设我们有一个类似这样的列表 [EdgeImpl(1,2), EdgeImpl(3,4)]

我想将它列在 [EdgeImpl(2,1), EdgeImpl(4,3)] 中。这正是反向方法的作用。

除了

我不能编辑接口和实现,所以我不能添加一个 set 方法,它必须是 IN-PLACED。

我的尝试失败了,因为我无法使用 get 方法进行交换。我很困惑如何交换它们

有什么帮助吗?

【问题讨论】:

  • 因为你没有setter方法,也不能改变实现。我认为唯一的办法就是反思
  • 如果您的任务是反转List,那么Edge 的相关性如何。至少你是这样解释的。我建议你问你的老师澄清一下。

标签: java interface


【解决方案1】:

如果您无法更改现有的EdgeImpl,请创建新的!

我认为您所说的“就地”是指不能返回新列表,必须修改传入的列表。应该允许您创建新的EdgeImpls。如果不是,那将涉及反射,这不是微不足道的。

public static void reverse(List<Edge> graph) {
    for (int i = 0 ; i < graph.size() ; i++) {
        int temp1 = graph.get(i).getFirstNode();
        int temp2 = graph.get(i).getSecondNode();
        EdgeImpl newEdge = new EdgeImpl(temp2, temp1);
        graph.set(i, newEdge); // this overwrites the element in the list at position i.
    }
}

【讨论】:

  • 这算作就地吗?
  • @ABC 请参阅第 2 段,了解为什么我认为这很重要。
猜你喜欢
  • 1970-01-01
  • 2017-04-06
  • 2021-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-27
相关资源
最近更新 更多