ClassCastException : 不能转换为 java.lang.Integer

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29666610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:41:43  来源:igfitidea点击:

ClassCastException : cant be cast to java.lang.Integer

java

提问by fuschia

I know this has been asked a lot in stackoverflow but I could not find answers that work to my problem.

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

In the following code below, I cant print out each item in ArrayList<Integer>because it says that "Edge cannot be cast to java.lang.Integer".

在下面的代码中,我无法打印出每个项目,ArrayList<Integer>因为它说"Edge cannot be cast to java.lang.Integer".

I have tried to print each item using for(Integer item :p1)and also for (int item: p1)but both did not work.

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

I think maybe the problem is because of the toString()method in Edge class but if i do not use toString()I cant get the real key number (it will be printed as Edge@28a418fcor something like this)

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

Thanks for helping before

感谢之前的帮助

Main class

主班

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); 
        }

    }
}

Edge class

边缘类

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;
    }
}

Graph class

图类

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

Node class

节点类

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;
      }
}

回答by Radiodef

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);

Ultimately, this is a classic example of why raw types are bad. You've got an ArrayList<Integer>and you put Edges in it.

最终,这是原始类型为什么不好的经典示例。你有一个,ArrayList<Integer>然后你把Edges放进去。

Unfortunately, I don't know how to tell you how to fix it since I don't understand what you're trying to do.

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

回答by Giovanni

the error lies here

错误就在这里

  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

later in the code you get the ArrayList out of the Map as ArrayList but it an ArrayList containing Edge try to change

稍后在代码中,您将 ArrayList 作为 ArrayList 从 Map 中取出,但它包含 Edge 的 ArrayList 尝试更改

tmp = new ArrayList();

to

tmp = new ArrayList<Integer>();

you should get a compilation error when adding an Edge to it

向其添加 Edge 时,您应该会收到编译错误

回答by chilltouch

    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;
}

This should work. I don't have a lot of time to search for an explanation.

这应该有效。我没有太多时间去寻找解释。

回答by alfasin

You declare:

你声明:

int from;
int to;
int type;

and you should declare them as Integers instead:

你应该将它们声明为Integers :

Integer from;
Integer to;
Integer type;

because later on you're doing:

因为后来你正在做:

this.from = new Integer(from);

etc.

等等。

A better option would be to change the assignment to:

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

this.from = from;

which would also solve this error since you would be assigning an intto an int. Is there a purpose you're using new Integer()? because if not - I would suggest removing it - it's slower (performance-wise) comparing to the primitive int.

这也将解决这个错误,因为你会被分配一个int到的int。你有什么用途new Integer()吗?因为如果不是 - 我建议删除它 - 与原始int.

Bottom line: stay consistent and either use intthroughout the code, or Integer- try not to mix them unless it's really required.

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