简体   繁体   English

如何在Java中将对象转换为int?

[英]How can i convert an object to an int in Java?

I'm working in Java and I would like to convert an Object to an int . 我正在使用Java,我想将Object转换为int

I do: 我做:

   Collection c = MyHashMap.values(); 
   Object f = Collections.max(c);
   int NumOfMaxValues = Integer.parseInt(f);

But it's not working. 但它不起作用。 It says: No suitable method for parseInt. 它说: No suitable method for parseInt.

How can I fix that? 我该如何解决这个问题?

Integer.parseInt()

expects a String . 期待一个String You can use 您可以使用

Integer.parseInt(f.toString())

and override the toString() method in your class. 并覆盖类中的toString()方法。

Ideally, you should use generics to your advantage and have something along the lines of the below: 理想情况下,您应该使用泛型来获得优势并具有以下内容:

Map<Object,Integer> myHashMap = new HashMap<Object,Integer>();
Collection<Integer> values = myHashMap.values();
Integer value = Collections.max(values);
if (value != null)
{
  int myInt = value;
}

You can't just convert any object to an int. 您不能只将任何对象转换为int。 How should that work. 应该怎么做 Think of a class like this: 想想这样一个类:

class Car {
  public String name;
  public String owner;
}

You need to define a method yourself. 您需要自己定义一个方法。 Or you have to find out what specific object that is and how to convert it. 或者您必须找出具体的对象以及如何转换它。

Integer.parseInt(f.toString());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM