ClassCastException:无法转换为java.lang.Integer

ClassCastException:无法转换为java.lang.Integer,java,Java,我知道这在stackoverflow中被问了很多,但我找不到解决我问题的答案 在下面的代码中,我无法打印出ArrayList中的每个项目,因为它说“Edge不能转换为java.lang.Integer” 我曾尝试使用for(Integer item:p1)和for(int item:p1)打印每个项目,但都不起作用 我想问题可能是因为Edge类中的toString()方法,但是如果我不使用toString()我就无法获得真正的密钥号(它将被打印为Edge@28a418fc或类似的内容) 谢谢你以

我知道这在stackoverflow中被问了很多,但我找不到解决我问题的答案

在下面的代码中,我无法打印出
ArrayList
中的每个项目,因为它说
“Edge不能转换为java.lang.Integer”

我曾尝试使用
for(Integer item:p1)
for(int item:p1)
打印每个项目,但都不起作用

我想问题可能是因为Edge类中的
toString()
方法,但是如果我不使用
toString()
我就无法获得真正的密钥号(它将被打印为
Edge@28a418fc
或类似的内容)

谢谢你以前的帮助

主类

public class Ranker7 {

    static Graph g;
    static Node n;
    static Edge e;
    static HashMap<Integer, Node> nodeMap; 
    int id;
    static double weight;
    static int year;
    static int type;

    Ranker7() {
            g = new Graph();
            nodeMap = new HashMap<Integer, Node>();
            n = new Node(id,year,type,weight);
    }

    public static void main (String[] args) throws Exception{

        long startTime = System.currentTimeMillis();

        /**Rule Mining**/
        Ranker7 Ranker = new Ranker7();
        Connection connect = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        PreparedStatement preparedStatement2 = null;
        ResultSet resultSet2 = null;
        HashMap nodeMap =  new HashMap();  

        System.out.println("Processing...");
        Class.forName("com.mysql.jdbc.Driver");
        connect = DriverManager.getConnection("jdbc:mysql://localhost/arnetminer?"+"user=root&password=1234");
        preparedStatement = connect.prepareStatement("Select fr,t,ty from subedge");

        resultSet = preparedStatement.executeQuery();
        int i=0;

        while(resultSet.next()) {
           g.addEdgeForIndexing(resultSet.getInt(1),resultSet.getInt(2),resultSet.getInt(3));         
           i++;             
           System.out.println( "edges added to G = "+i);
        }       

        System.out.println("Loaded " + g.nodeCount() + " nodes.");

        preparedStatement = connect.prepareStatement("Select node,year,type from subnode2");
        resultSet = preparedStatement.executeQuery();
        int h=0;
        while(resultSet.next()) {
               Node n = new Node(resultSet.getInt(1), resultSet.getInt(2),resultSet.getInt(3),weight);
               int key1=resultSet.getInt(1);
               nodeMap.put(key1,n);
               h++;             
        }

        System.out.println(nodeMap);
        System.out.println(nodeMap.size());

        Scanner sc = new Scanner(System.in);

        System.out.println("How many authors do you want to enter?");
        int num = sc.nextInt();
        int[] authorNames = new int[num];
        for(int a = 0; a < authorNames.length; a++){
            System.out.println("Enter author name:");
            authorNames[a] = sc.nextInt();
        }

        System.out.println("Year : ");
        int inputYear3 = sc.nextInt();

        ArrayList<Integer> p1 = new ArrayList<Integer>();
        /**Get the papers written by input author A-P**/    
        for(int b=0; b< authorNames.length;b++){
            int AuthorID1 = authorNames[b];
            p1 = g.getOutEdgesToP(AuthorID1);
        }

        for(int item : p1){ //the error of classcastexception is here
            System.out.println(item); 
        }

    }
}
public class Edge {


    int from;
    int to;
    int type;
    private static int counter = 0;
    public Edge(int from, int to, int type) {
        this.from = from;
        this.to = to;
        this.type = type;
    //  System.out.println("edges added from " + from + " to " +  to + " with type "+ type);
    }

    public String toString(){
        String repr = Integer.toString(to);
        return repr;
    }
    public int getfrom(){
        return from;
    }

    public int getto(){
        return to;
    }

    public int getType(){
        return type;
    }

    public void setfrom(int from){
        this.from = from;
    }

    public void setto(int to){
        this.to = to;
    }

    public void setType(int type){
        this.type = type;
    }
}
import java.lang.reflect.Field;
import java.util.*;

public class Graph {

    private HashSet<Integer>  nodeIDs;   
    public HashMap<Integer, String> nodeIDsWithTN;
    public HashMap<Integer, String> TNMap;  
    private HashMap<Integer, ArrayList<Integer>>  edges;
    private HashMap<Integer, ArrayList<Integer>>  reverse;
    private int numNodes;
    private int numEdges;
    private int numReverse;

    public Graph() {
        edges = new HashMap<Integer, ArrayList<Integer>>();
        reverse = new HashMap<Integer, ArrayList<Integer>>();
        nodeIDs = new HashSet<Integer>();
        nodeIDsWithTN = new HashMap<Integer, String>();
        TNMap = new HashMap<Integer, String>();
        new HashSet();
    }

    public void addEdgeForIndexing(int from, int to, int T) throws IllegalArgumentException, IllegalAccessException {   

            Edge e = new Edge(from,to,T);
            nodeIDs.add(e.from);
            nodeIDs.add(e.to);

            ArrayList tmp = null;
            if (edges.containsKey(e.from))
              tmp = (ArrayList) edges.get(e.from);
            else {
              tmp = new ArrayList();
              edges.put(e.from,tmp);
            }
            tmp.add(e);

            ArrayList tmp2 = null;
            if (reverse.containsKey(e.to))
              tmp2 = (ArrayList) reverse.get(e.to);
            else {
              tmp2 = new ArrayList();
              reverse.put(e.to,tmp2);
            }
            tmp2.add(e);

    }

    public int nodeCount() {
        if(nodeIDs.size() > 0) 
            return nodeIDs.size();
            // else return numNodes;
        return numEdges;
    }

    public int countInEdges(Integer key) {
        if (!reverse.containsKey(key)) return 0;
            return ((ArrayList<?>) reverse.get(key)).size();
    }

    public int countOutEdges(Integer key) {
        if (!edges.containsKey(key)) return 0;
            return ((ArrayList<?>) edges.get(key)).size();
    }
/**
    public ArrayList<String> getInEdgesFromPtoA(String id) {
        if (!reverse.containsKey(id)) return null;  
            ArrayList<String> a = reverse.get(id);
            ArrayList<String> result = new ArrayList<String>();
                for(int j=0;j<a.size();j++){
                      if(a.get(j).startsWith("A")){
                          result.add(a.get(j));                           
                      }
                 }
        return result;
    }
**/

      public ArrayList<Integer> getOutEdges(Integer key) {
            if (!edges.containsKey(key)) 
                return null;

            ArrayList<Integer> value = edges.get(key);
            return value;
      }


      public ArrayList<Integer> getOutEdgesToP(int id) {
            if (!edges.containsKey(id)) {
                return null;
            }

            ArrayList<Integer> a = edges.get(id);           
            System.out.println ("Arraylist a: " + a); //if i print using this its okay. but i cant get each item in this ArrayList like below
            for(int item : a){ //the error of classcastexception is here
                System.out.println(item);
            }

            return a;
     }

    public Iterator<Integer> nodeIteratorInitial() {
        return nodeIDs.iterator();
    }
}
public class Node {

      int id;
      double weight;
      int year;
      int type;
      private static int counter = 0;

      public Node(int id,int year,int type,double weight) {
          this.id = id;
          this.year=year;
          this.weight = weight;
          this.type = type;
     }

      @Override
      public String toString() {
          // here you can create your own representation of the object
          String repr = "id:" + id + ", year:" + year + ", weight:" + weight + ", node type:" + type;
          return repr;
          }

    public double getWeight(){
            return weight;
      }

      public int getid() {
           return id;
      }

      public int getType() {
           return type;
      }

      public int getYear() {
           return year;
      }

      public void setWeight(double weight){
         this.weight=weight;
      }

      public void setid(int id){
          this.id=id;
      }

      public void setType() {
           this.type=type;
      }
}
图形类

public class Ranker7 {

    static Graph g;
    static Node n;
    static Edge e;
    static HashMap<Integer, Node> nodeMap; 
    int id;
    static double weight;
    static int year;
    static int type;

    Ranker7() {
            g = new Graph();
            nodeMap = new HashMap<Integer, Node>();
            n = new Node(id,year,type,weight);
    }

    public static void main (String[] args) throws Exception{

        long startTime = System.currentTimeMillis();

        /**Rule Mining**/
        Ranker7 Ranker = new Ranker7();
        Connection connect = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        PreparedStatement preparedStatement2 = null;
        ResultSet resultSet2 = null;
        HashMap nodeMap =  new HashMap();  

        System.out.println("Processing...");
        Class.forName("com.mysql.jdbc.Driver");
        connect = DriverManager.getConnection("jdbc:mysql://localhost/arnetminer?"+"user=root&password=1234");
        preparedStatement = connect.prepareStatement("Select fr,t,ty from subedge");

        resultSet = preparedStatement.executeQuery();
        int i=0;

        while(resultSet.next()) {
           g.addEdgeForIndexing(resultSet.getInt(1),resultSet.getInt(2),resultSet.getInt(3));         
           i++;             
           System.out.println( "edges added to G = "+i);
        }       

        System.out.println("Loaded " + g.nodeCount() + " nodes.");

        preparedStatement = connect.prepareStatement("Select node,year,type from subnode2");
        resultSet = preparedStatement.executeQuery();
        int h=0;
        while(resultSet.next()) {
               Node n = new Node(resultSet.getInt(1), resultSet.getInt(2),resultSet.getInt(3),weight);
               int key1=resultSet.getInt(1);
               nodeMap.put(key1,n);
               h++;             
        }

        System.out.println(nodeMap);
        System.out.println(nodeMap.size());

        Scanner sc = new Scanner(System.in);

        System.out.println("How many authors do you want to enter?");
        int num = sc.nextInt();
        int[] authorNames = new int[num];
        for(int a = 0; a < authorNames.length; a++){
            System.out.println("Enter author name:");
            authorNames[a] = sc.nextInt();
        }

        System.out.println("Year : ");
        int inputYear3 = sc.nextInt();

        ArrayList<Integer> p1 = new ArrayList<Integer>();
        /**Get the papers written by input author A-P**/    
        for(int b=0; b< authorNames.length;b++){
            int AuthorID1 = authorNames[b];
            p1 = g.getOutEdgesToP(AuthorID1);
        }

        for(int item : p1){ //the error of classcastexception is here
            System.out.println(item); 
        }

    }
}
public class Edge {


    int from;
    int to;
    int type;
    private static int counter = 0;
    public Edge(int from, int to, int type) {
        this.from = from;
        this.to = to;
        this.type = type;
    //  System.out.println("edges added from " + from + " to " +  to + " with type "+ type);
    }

    public String toString(){
        String repr = Integer.toString(to);
        return repr;
    }
    public int getfrom(){
        return from;
    }

    public int getto(){
        return to;
    }

    public int getType(){
        return type;
    }

    public void setfrom(int from){
        this.from = from;
    }

    public void setto(int to){
        this.to = to;
    }

    public void setType(int type){
        this.type = type;
    }
}
import java.lang.reflect.Field;
import java.util.*;

public class Graph {

    private HashSet<Integer>  nodeIDs;   
    public HashMap<Integer, String> nodeIDsWithTN;
    public HashMap<Integer, String> TNMap;  
    private HashMap<Integer, ArrayList<Integer>>  edges;
    private HashMap<Integer, ArrayList<Integer>>  reverse;
    private int numNodes;
    private int numEdges;
    private int numReverse;

    public Graph() {
        edges = new HashMap<Integer, ArrayList<Integer>>();
        reverse = new HashMap<Integer, ArrayList<Integer>>();
        nodeIDs = new HashSet<Integer>();
        nodeIDsWithTN = new HashMap<Integer, String>();
        TNMap = new HashMap<Integer, String>();
        new HashSet();
    }

    public void addEdgeForIndexing(int from, int to, int T) throws IllegalArgumentException, IllegalAccessException {   

            Edge e = new Edge(from,to,T);
            nodeIDs.add(e.from);
            nodeIDs.add(e.to);

            ArrayList tmp = null;
            if (edges.containsKey(e.from))
              tmp = (ArrayList) edges.get(e.from);
            else {
              tmp = new ArrayList();
              edges.put(e.from,tmp);
            }
            tmp.add(e);

            ArrayList tmp2 = null;
            if (reverse.containsKey(e.to))
              tmp2 = (ArrayList) reverse.get(e.to);
            else {
              tmp2 = new ArrayList();
              reverse.put(e.to,tmp2);
            }
            tmp2.add(e);

    }

    public int nodeCount() {
        if(nodeIDs.size() > 0) 
            return nodeIDs.size();
            // else return numNodes;
        return numEdges;
    }

    public int countInEdges(Integer key) {
        if (!reverse.containsKey(key)) return 0;
            return ((ArrayList<?>) reverse.get(key)).size();
    }

    public int countOutEdges(Integer key) {
        if (!edges.containsKey(key)) return 0;
            return ((ArrayList<?>) edges.get(key)).size();
    }
/**
    public ArrayList<String> getInEdgesFromPtoA(String id) {
        if (!reverse.containsKey(id)) return null;  
            ArrayList<String> a = reverse.get(id);
            ArrayList<String> result = new ArrayList<String>();
                for(int j=0;j<a.size();j++){
                      if(a.get(j).startsWith("A")){
                          result.add(a.get(j));                           
                      }
                 }
        return result;
    }
**/

      public ArrayList<Integer> getOutEdges(Integer key) {
            if (!edges.containsKey(key)) 
                return null;

            ArrayList<Integer> value = edges.get(key);
            return value;
      }


      public ArrayList<Integer> getOutEdgesToP(int id) {
            if (!edges.containsKey(id)) {
                return null;
            }

            ArrayList<Integer> a = edges.get(id);           
            System.out.println ("Arraylist a: " + a); //if i print using this its okay. but i cant get each item in this ArrayList like below
            for(int item : a){ //the error of classcastexception is here
                System.out.println(item);
            }

            return a;
     }

    public Iterator<Integer> nodeIteratorInitial() {
        return nodeIDs.iterator();
    }
}
public class Node {

      int id;
      double weight;
      int year;
      int type;
      private static int counter = 0;

      public Node(int id,int year,int type,double weight) {
          this.id = id;
          this.year=year;
          this.weight = weight;
          this.type = type;
     }

      @Override
      public String toString() {
          // here you can create your own representation of the object
          String repr = "id:" + id + ", year:" + year + ", weight:" + weight + ", node type:" + type;
          return repr;
          }

    public double getWeight(){
            return weight;
      }

      public int getid() {
           return id;
      }

      public int getType() {
           return type;
      }

      public int getYear() {
           return year;
      }

      public void setWeight(double weight){
         this.weight=weight;
      }

      public void setid(int id){
          this.id=id;
      }

      public void setType() {
           this.type=type;
      }
}
您声明:

int from;
int to;
int type;
您应该将它们声明为
Integer
s:

Integer from;
Integer to;
Integer type;
因为以后你会做:

this.from = new Integer(from);
等等

更好的选择是将分配更改为:

this.from = from;
这也将解决此错误,因为您将
int
分配给
int
。您使用的
新整数()
有什么用途吗?因为如果不是,我建议删除它,它比原语
int
慢(性能方面)

底线:保持一致,或者在整个代码中使用
int
,或者
Integer
——除非确实需要,否则不要将它们混合使用。

私有哈希映射边缘;
private HashMap<Integer, ArrayList<Integer>>  edges;

// ...later

Edge e = new Edge(from,to,T);

// ...later

else {
    tmp = new ArrayList();
    edges.put(e.from,tmp);
}
tmp.add(e);
//……以后 边e=新边(从,到,T); //……以后 否则{ tmp=newarraylist(); 边缘。放置(例如,从,tmp); } tmp.add(e)
归根结底,这是一个典型的例子。您有一个
ArrayList
并将
Edge
s放入其中

不幸的是,我不知道如何告诉您如何修复它,因为我不明白您试图做什么。

错误就在这里

  public void addEdgeForIndexing(int from, int to, int T) throws IllegalArgumentException, IllegalAccessException {   

            Edge e = new Edge(from,to,T);
            nodeIDs.add(e.from);
            nodeIDs.add(e.to);

            ArrayList tmp = null;
            if (edges.containsKey(e.from))
              tmp = (ArrayList) edges.get(e.from);
            else {
              tmp = new ArrayList();
              edges.put(e.from,tmp);
            }
            tmp.add(e);//adding an edge to tmp
在代码的后面部分,您将从映射中获取ArrayList作为ArrayList,但它是一个包含边的ArrayList 尝试改变

tmp = new ArrayList();

tmp=newarraylist();
向其添加边缘时,应该会出现编译错误{
    public ArrayList<Integer> getOutEdgesToP(int id) {
if (!edges.containsKey(id)) {
    return null;
}
System.out.println(edges.get(id));
ArrayList<Integer> a = edges.get(id);
System.out.println("Arraylist a: " + a); // if i print using this its
                     // okay. but i cant get each
                     // item in this ArrayList like
                     // below
for (Object item : a) { // the error of classcastexception is here
    System.out.println(item);
}

return a;
}
如果(!edges.containsKey(id)){ 返回null; } System.out.println(edges.get(id)); ArrayList a=edges.get(id); System.out.println(“Arraylist a:+a);//如果我使用它来打印 //好的,但我不能每一个都买 //此ArrayList中的项类似于 //下面 对于(objectitem:a){//classcastexception的错误在这里 系统输出打印项次(项); } 返回a; }
这应该行得通。我没有太多的时间来寻找解释。

您是否尝试了` for(Integer item:p1)`而不是` for(int item:p1)`?@mtyurt是的,我尝试了两种方法。.您使用了很多原始类型。。。为什么?(例如,在Graph#addEdgeForIndexing中)@Tom我创建了程序,但对于addEdgeForIndexing方法,我实际上从其他地方获得了参考。我会努力解决的,谢谢你。@fuschia原始类型通常是邪恶的源头,所以你应该尽量避免它们。我想这个问题是一个很好的例子,为什么这会导致问题:)。根据你的建议,我将所有内容都更改为int,因为我需要更好的性能。另外,我也没有使用new Integer()的真正原因。但是ClassCastException的问题仍然无法解决。谢谢,但我想我可能还遗漏了一些东西。@fuschia请发布类
Node
的代码,以及我创建的程序,但对于addEdgeForIndexing方法,我实际上从其他地方得到了参考。我会尽力解决的,谢谢。我想,再检查一下逻辑。例如,
edges
应该是一个
HashMap
。很好@fuschia正如Radiodef所提到的,使用原始类型是一种糟糕的做法(结果就是你现在所处的混乱局面)。对每个集合/映射使用泛型,这些错误将在编译时被捕获,并且会更清晰+(2-1)更多,因为我不明白你想做什么。谢谢所有这些都是问题所在!当我为tmp定义类型时,它现在可以工作了,但我的程序中现在有一个逻辑错误。我会设法解决的。重要的是ClassCastException问题解决了!谢谢!谢谢,这就是问题所在!当我为tmp定义类型时,它现在可以工作了,但我的程序中现在有一个逻辑错误。我会设法解决的。重要的是ClassCastException问题解决了!谢谢!非常感谢。但是我实际上需要它是int,这样性能会更好,因为我需要在那里循环很多项。