如何从另一个类修改私有变量?

时间:2015-12-03 22:36:44

标签: java object graph private shuffle

我正在为作业编写代码,我的老师写了一个有公共构造函数的课程。但是,构造函数中的变量是私有的。我试图改组一个对象的数组,但因为它是私有的,我无法修改它。如果我无法修改我的老师写的代码有没有办法做到这一点?

这是我老师班级的构造函数和变量:

private final int V;
private int E;
private Bag<Integer>[] adj;

/**
 * Initializes an empty graph with <tt>V</tt> vertices and 0 edges.
 * param V the number of vertices
 * @throws java.lang.IllegalArgumentException if <tt>V</tt> < 0
 */
public Graph(int V) {
    if (V < 0) throw new IllegalArgumentException("Number of vertices must be nonnegative");
    this.V = V;
    this.E = 0;
    adj = (Bag<Integer>[]) new Bag[V];
    for (int v = 0; v < V; v++) {
        adj[v] = new Bag<Integer>();
    }
}

这是我正在制作的方法:

public boolean tryImprove(double secs) {
    int size = G.V(); //V() returns the number of vertices of the graph
    Graph gTemp = G;
    Bag<Integer>[] adj = new Bag[size];
    for (int i = 0; i < size; i++) {
        adj[i] = (Bag<Integer>) G.adj(i);
    }
    gTemp.adj = adj; //this is where I'm having trouble with the private array
    while (System.currentTimeMillis() <= secs) {
        gTemp.adj = shuffle(adj, size);
        this.color = greedyColoring(gTemp);
        if (maxColor < greedyMax) return true;
    }
    // TODO: implement some graph coloring heuristic here.
    // Minimal good enough: do repeated trials of greedy-coloring,
    // each time with a random vertex order.  If you find a better
    // coloring (better than your previous best), return true.  Or
    // else if you run out of time, return false.

    // Note you can use System.currentTimeMillis() to estimate how
    // much time you have used.  For an example of its use, see
    // the code in main.

    return false;
}

adj(int v)方法(在老师的班级中):

public Iterable<Integer> adj(int v) {
    validateVertex(v);
    return adj[v];
}

greedyColoring(图G)方法(由老师编写,无法改变):

private static int[] greedyColoring(Graph G)
{
    int V = G.V();
    assert V >= 1;
    // This will be our coloring array.
    int[] color = new int[V];
    // In loop, we keep track of the maximum color used so far.
    int maxColor = 0;
    // For each vertex v, we let color[v] be the first color which
    // is not already taken by the neighbors of v.
    for (int v=0; v<V; ++v) {
        boolean[] taken = new boolean[maxColor+1];
        for (int u: G.adj(v))
            taken[color[u]] = true;
        // Find the first color c not taken by neighbors of v.
        int c = 1;
        while (c <= maxColor && taken[c])
            ++c;
        color[v] = c;
        // Maybe we started using a new color at v.
        if (c > maxColor)
            maxColor = c;
    }

    // All done, return the array.
    return color;
}

如果无法对对象的私有数组进行洗牌,那么是否有人建议我如何使用混洗索引调用图形对象上的greedyColoring(不确定我是否正确地表达了这一点)?

谢谢!

0 个答案:

没有答案