实例化私有类 - >空指针异常 [英] Instantiated private class -> null pointer exception

查看:134
本文介绍了实例化私有类 - >空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

真棒人!



我遇到问题...当我的测试用例达到 connectNodes方法中的allEdges.add(newEdge); 。

我认为它与 Edge newEdge = new Edge(n1,n2,weight); 之前有关用同样的方法。



问题是我在Edge类中使用泛型还是类似的东西?
我以前在 Edge newEdge = new Edge(n1,n2,weight); 这一行发表了一个错误消息,指出类似class not found。但是现在我好像在 allEdges.add(newEdge); 中得到了NullPointerException,而没有改变任何东西。



非常感谢您的帮助!

  import java.util。*; 

公共类MyMiniGraph< T扩展了Comparable< super T>>实现MiniGraph< T>
{
//包含所有节点及其边的图形
private Map< T,HashSet< Edge> > theGraph =新的HashMap< T,HashSet< Edge> >();
//跟踪图的当前大小
private int currentSize = 0;
//跟踪当前边数量
private int numEdges;
//包含所有边的TreeSet
私有TreeSet< Edge> allEdges;
//边表示具有关联节点和权重的类
私有类Edge实现Comparable< Edge>
{
public int cost;
public T n1;
public T n2;
public Edge(T n1,T n2,int cost)
{
this.n1 = n1;
this.n2 = n2;
this.cost =费用;
}

public int compareTo(Edge e)
{
//如果边相等则返回0
if(e.cost == cost)
返回0;
//如果边缘大于其他边缘则返回1,
// -1如果边缘小于其他边缘
返回e.cost<成本? 1:-1;
}

}

/ **
*向图中添加节点的方法。
*默默地忽略任何重复项
*
* @param n要添加到图中的节点。
* /
public void addNode(T n)
{
if(n == null)
throw new IllegalStateException(Invalid Node);
if(!theGraph.containsKey(n))
{
theGraph.put(n,new HashSet< Edge>());
++ currentSize;
}
}

/ **
*从图中删除一个节点的方法。
*在删除节点之前,必须删除与节点
*相关联的所有边。
*默默地忽略不在图中的任何节点。
* /
public void removeNode(T n)
{
if(theGraph.containsKey(n))
{
//如果节点n有边缘,删除所有这些边缘。
//首先,从其他节点删除连接到此
//节点的边,然后删除此节点
//及其边。
if(!theGraph.get(n).isEmpty())
{
//迭代器遍历节点n的边界
Iterator< Edge> edgeIt = theGraph.get(n).iterator();

//将此节点从其所有连接节点边缘列表中删除
Edge localEdge;
/ ** Edge foreignEdge; * /
while(edgeIt.hasNext())
{
localEdge = edgeIt.next();
T foreignNode = localEdge.n2 == n? localEdge.n1:localEdge.n2;
//迭代器遍历n(foreignNode)
/ ** Iterator< Edge>相邻节点的边缘。 forEdgeIt =
theGraph.get(foreignNode).iterator(); (forEdgeIt.hasNext())
{
foreignEdge = forEdgeIt.next();


if(foreignEdge.equals(localEdge))
forEdgeIt.remove();
} * /
//删除所有外部节点中出现的所有边。
theGraph.get(foreignNode).remove(localEdge);
allEdges.remove(localEdge);
--numEdges;


//删除节点本身,从而删除它的本地边界列表
theGraph.remove(n);
--currentSize;
}
}

/ **
*在两个节点之间创建单向边的方法。
*
* @param n1在
* @param n2之间创建边的第一个节点在
* @param之间创建边的第二个节点重量遍历如果(!包含(n1)||!包含(n2))
$ /
public void connectNodes(T n1,T n2,int weight)
{
$ b抛出新的IllegalStateException(节点不在图中);

if(!edgeExistsBetween(n1,n2))
{
Edge newEdge = new Edge(n1,n2,weight);
theGraph.get(n1).add(newEdge);
theGraph.get(n2).add(newEdge);

allEdges.add(newEdge);
++ numEdges;
}
}

/ **
*删除两个节点之间的边的方法。
*
* @param n1标识边的第一个节点。
* @param n2标识边的第二个节点。
* /
public void disconnectNodes(T n1,T n2)
{
if(!contains(n1)||!contains(n2))
throw new IllegalStateException(节点不在图中);

布尔型n1n2EdgeExists = true;

//在n1上迭代,从n2中移除包含n2的所有边
Iterator< Edge> edgeIt = theGraph.get(n1).iterator();

Edge deadEdge = null;
while(edgeIt.hasNext())
{
deadEdge = edgeIt.next();

if(deadEdge.n1.equals(n1))
theGraph.get(n2).remove(deadEdge);

else if(deadEdge.n2.equals(n1))
theGraph.get(n1).remove(deadEdge);

else
n1n2EdgeExists = false;
}
if(n1n2EdgeExists){
//从n1中删除n1-n2边缘
theGraph.get(n1).remove(deadEdge);

allEdges.remove(deadEdge);
--numEdges;
}

}

/ **
*用于搜索某个节点的图形的方法。
*如果节点存在于图中,则该方法返回
* true,否则返回false。
*
* @return boolean如果图形包含n,则返回true,否则返回false。
* /
public boolean contains(T n)
{
return theGraph.containsKey(n);
}

/ **
*查找图中节点数量的方法。
*
* @returns int图中节点的数量。
* /
public int size()
{
return currentSize;
}

/ **
*检查节点n1和n2之间是否存在边。
*用于测试目的。
*
* @param n1标识边的第一个节点。
* @param n2标识边的第二个节点。
* @return如果和n1和n2之间存在边缘,则返回true,否则返回false。
* /
public boolean edgeExistsBetween(T n1,T n2)
{
if(contains(n1))
{
boolean n1ContainsN2 = false;

迭代器< Edge> edgeIt = theGraph.get(n1).iterator();

边缘adjToN1;
while(edgeIt.hasNext())
{
adjToN1 = edgeIt.next();
if(adjToN1.n1.equals(n2))
n1ContainsN2 = true;
else if(adjToN1.n2.equals(n2))
n1ContainsN2 = true;
else
;
} // // n1有下一条边
return n1ContainsN2;
} //如果
中的n1返回false;
}

/ **
*获取图形中的边数。
*用于测试目的。
*
* @返回图中边的数量。
* /
public int getNumberOfEdges()
{
return numEdges;
}

/ **
*计算图的最小生成树的方法。
*该方法应该返回一个表示
*最小生成树的字符串。该方法不允许在计算过程中修改
*图形,即。在调用
*方法之前,原始图必须与
*相同。
*
*最小生成树使用Kruskal算法计算。
*
* @return Graph Graph类的新实例,表示
*最小生成树。
* /
public MyMiniGraph< T> generateMinimumSpanningTree()
{
int edgesAccepted = 0;
//给所有节点提供表示不相交集合的类
DisjSet< T> ds = new DisjSet< T>(theGraph.keySet());

//设置一个新图来表示最小生成树
MyMiniGraph< T> minSpanTree = new MyMiniGraph< T>();
//用所有的图形节点初始化minSpanTree
Iterator< T> nodeIter = theGraph.keySet()。iterator();
while(nodeIter.hasNext())
minSpanTree.addNode(nodeIter.next());

//在优先级队列中排列图中的所有边
PriorityQueue< Edge> pq =新的PriorityQueue< Edge>(allEdges);
Edge e;

// Kruskals算法。如果它们不是引起循环的同一个集合的一部分,则接受
//的最小边。
while(edgesAccepted< currentSize -1)
{
e = pq.poll();
T uset = ds.find(e.n1);
T vset = ds.find(e.n2);

if(uset!= vset)
{
//接受边缘
edgesAccepted ++;
ds.union(uset,vset);

//如果边缘被接受,将其添加到minSpanTree
minSpanTree.connectNodes(e.n1,e.n2,e.cost);
}
}
返回minSpanTree;
}

}

解决方案

我没有找到任何将成员allEdges初始化为有效的TreeSet对象的地方。尝试初始化(适当的地方看起来就像你在哪里定义它)


Hi awesome person!

I have a problem... I get a NullPointerException when my test case reaches allEdges.add(newEdge); in the connectNodes method.

I think it has something to do with Edge newEdge = new Edge( n1, n2, weight ); previously in that same method.

Is the problem my use of generics in the Edge class or something like that?. I previously got an error directing me at the Edge newEdge = new Edge( n1, n2, weight ); line, saying something like "class not found". But now i seem to get the NullPointerException at allEdges.add(newEdge); instead without having changed anything.

Very thankful for every bit of help!

import java.util.*;

public class MyMiniGraph<T extends Comparable<? super T>> implements MiniGraph<T>
{
      // The Graph containing all the nodes and their edges
    private Map< T, HashSet<Edge> > theGraph = new HashMap< T, HashSet<Edge> >( );
      // Keeps track of theGraphs current size
    private int currentSize = 0;
      // Keeps track of the current Edge quantity
    private int numEdges;
      // TreeSet containing all edges
    private TreeSet<Edge> allEdges;
      // edge representing class with its associated nodes and weight
    private class Edge implements Comparable<Edge>
    {
        public int cost;
        public T n1;
        public T n2;
        public Edge(T n1, T n2 , int cost)
        {
            this.n1 = n1;
            this.n2 = n2;
            this.cost = cost;
        }

    public int compareTo(Edge e)
    {
          // returns 0 if edges are equal
        if(e.cost == cost)
            return 0;
          // returns 1 if edge is greater than other edge,
          // -1 if edge is smaller than other edge
        return e.cost < cost ? 1 : -1; 
    }

}

/** 
 *  Method for adding a node to the graph.
 *  Silently ignores any duplicates
 *
 *  @param n    The node to add to the graph.
 */
public void addNode(T n)
{
    if(n == null)
        throw new IllegalStateException("Invalid Node");
    if(!theGraph.containsKey(n))
    {   
        theGraph.put(n,new HashSet<Edge>());
        ++currentSize;
    }
}

/**
 *  Method for removing a node from the graph. 
 *  Before the node is removed, all edges associated with the node
 *  must be removed.
 *  Silently ignores any nodes not already in the graph.
 */
public void removeNode(T n)
{
    if(theGraph.containsKey(n))
    {
      // If node n has edges, remove all those edges. 
      // Firstly, remove the edges connecting to this 
      // node from other nodes, then, remove this node  
      // and its edges with it.
        if( !theGraph.get(n).isEmpty() )
        {
              //iterator to iterate over the edges of node n
            Iterator<Edge> edgeIt = theGraph.get(n).iterator();

              // remove this node from all its connecting nodes edge lists
            Edge localEdge;
            /**Edge foreignEdge;*/
            while(edgeIt.hasNext())
            {
                localEdge = edgeIt.next();
                T foreignNode = localEdge.n2 == n ? localEdge.n1 : localEdge.n2;
                  // iterator to iterate over the edges of adjacent node of n (foreignNode)
                /**Iterator<Edge> forEdgeIt = 
                    theGraph.get(foreignNode).iterator();

                while(forEdgeIt.hasNext())
                {
                    foreignEdge = forEdgeIt.next();
                    if( foreignEdge.equals( localEdge ) )
                        forEdgeIt.remove();
                }*/
                  // removes all edges occurring in n from all foreign nodes
                theGraph.get(foreignNode).remove(localEdge);
                allEdges.remove(localEdge);
                --numEdges;
            }
        }
          //remove the node itself thereby also removing its local edge list
        theGraph.remove(n);
        --currentSize;
    }
}

/**
 *  Method for creating an unidirectional edge between two nodes. 
 *
 *  @param  n1  The first node to create an edge between
 *  @param  n2  The second node to create an edge between
 *  @param  weight  The cost for traversing the edge
 */
public void connectNodes(T n1, T n2, int weight)
{
    if(!contains(n1) || !contains(n2))
        throw new IllegalStateException("node not in graph");

    if(!edgeExistsBetween(n1,n2))
    {
        Edge newEdge = new Edge( n1, n2, weight );
        theGraph.get(n1).add( newEdge );
        theGraph.get(n2).add( newEdge );

        allEdges.add(newEdge);
        ++numEdges;
    }
}

/**
 *  Method for removing an edge between two nodes.
 *
 *  @param  n1  The first node that identifies the edge.
 *  @param  n2  The second node that identifies the edge.
 */
public void disconnectNodes(T n1, T n2)
{
    if(!contains(n1) || !contains(n2))
        throw new IllegalStateException("node not in graph");

    boolean n1n2EdgeExists = true;

  // iterates over n1, removing all edges containing n2 from n2
    Iterator<Edge> edgeIt = theGraph.get(n1).iterator();

    Edge deadEdge = null;
    while(edgeIt.hasNext())
    {
        deadEdge = edgeIt.next();

        if( deadEdge.n1.equals(n1) )
            theGraph.get(n2).remove(deadEdge);

        else if( deadEdge.n2.equals(n1) )
            theGraph.get(n1).remove(deadEdge);

        else
            n1n2EdgeExists = false;
    }
    if(n1n2EdgeExists){
          // removes the n1-n2 edge from n1
        theGraph.get(n1).remove(deadEdge);

        allEdges.remove(deadEdge);
        --numEdges;
    }

}

/**
 *  Method for searching the graph for a certain node.
 *  If the node is present in the graph, the method returns 
 *  true, otherwise, it returns false.
 * 
 *  @return boolean     true if the graph contains n, otherwise false. 
 */
public boolean contains(T n)
{
    return theGraph.containsKey(n);
}

/**
 *  Method for finding the number of nodes in the graph.
 * 
 *  @returns int    The number of nodes in the graph.
 */
public int size()
{
    return currentSize;
}

/**
 * Checks if there exists and edge between nodes n1 and n2.
 * Used for testing purposes.
 * 
 * @param n1    The first node that identifies the edge.
 * @param n2    The second node that identifies the edge.
 * @return true if and edge exists between n1 and n2, otherwise false.
 */
public boolean edgeExistsBetween(T n1, T n2)
{
    if(contains(n1))
    {
        boolean n1ContainsN2 = false;

        Iterator<Edge> edgeIt = theGraph.get(n1).iterator();

        Edge adjToN1;
        while(edgeIt.hasNext())
        {
            adjToN1 = edgeIt.next();
            if( adjToN1.n1.equals(n2) )
                n1ContainsN2 = true;
            else if( adjToN1.n2.equals(n2) )
                n1ContainsN2 = true;
            else
                ;
        }// while n1 has next edge
        return n1ContainsN2;
    }// if n1 in graph
    return false;
}

/**
 * Gets the number of edges in the graph.
 * Used for testing purposes.
 * 
 * @return the number of edges in the graph.
 */
public int getNumberOfEdges()
{
    return numEdges;
}

/**
 *  Method for calculating a minimum spanning tree for the graph.
 *  The method is supposed to returning a String representing the
 *  minimum spanning tree. The method is not allowed to modify the
 *  graph during the calculation, ie. the original graph must be
 *  identical to how the graph looked before the invocation of
 *  the method.
 *
 *  The minimum spanning tree is calculated using Kruskal's algorithm.
 *
 *  @return Graph A new instance of the Graph class, representing a
 *      minimal spanning tree.
 */
public MyMiniGraph<T> generateMinimumSpanningTree()
{
    int edgesAccepted = 0;
      //give all nodes to a class representing disjoint sets
    DisjSet<T> ds = new DisjSet<T>( theGraph.keySet() );

      //set up a new graph to represent the minimum spanning tree
    MyMiniGraph<T> minSpanTree = new MyMiniGraph<T>();
      //initialize minSpanTree with all theGraphs nodes
    Iterator<T> nodeIter = theGraph.keySet().iterator();
    while(nodeIter.hasNext())
        minSpanTree.addNode(nodeIter.next());

      //order all edges in theGraph in a priority queue
    PriorityQueue<Edge> pq = new PriorityQueue<Edge>(allEdges);
    Edge e;

      // Kruskals algorithm. Accepts the smallest edges in order
      // if they are not part of the same set which would cause a cycle. 
    while(edgesAccepted < currentSize -1)
    {
        e = pq.poll( );
        T uset = ds.find( e.n1 );
        T vset = ds.find( e.n2 );

        if(uset != vset)
        {
            // Accept the edge
            edgesAccepted++;
            ds.union(uset, vset);

             //if the edge is accepted, add it to minSpanTree
            minSpanTree.connectNodes(e.n1, e.n2, e.cost);
        }
    }
    return minSpanTree;
}

}

解决方案

I don't find any place where you initialize the member allEdges to a valid TreeSet object. Try to initialize (proper place seems like just where you define it)

这篇关于实例化私有类 - &gt;空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆