Cannot cast from int to MyClass - java

I have a problem in dealing with the conversion of integer to string. This is my code :
MyClass getRow;
getRow = (MyClass) getListAdapter().getCount();
I found an error on this line: Cannot cast from int to MyClass
This is my MyClass ListView Adapter :
public String toString() {
return myclass;
}
Solved
I have found a solution by adding a few tricks to convert an integer to a string, like this :
int i ;
i = getListAdapter().getCount();
String str = String.valueOf(i);
TextView totalRow = (TextView) findViewById(R.id.totalRow);
totalRow.setText(str);
thanks for all of your answers, awesome Stackoverflow !

int is a primitive and not a class, so the compiler is correct. Why do you expect that an int transform magically into MyClass? What are you trying to do here?
If I understand you correct, you must assing the value of getRow() to your class somehow (either via a setter, by constructor or by accessing the member) and then you can use MyClass. Of course if you want to convert the int to a String object, you have to convert it:
String s = String.valueof(integervalue);

You cannot cast an int to an Object. In the first row you mention you are exactly doing that. getCount() returns an int and you try to cast it to (MyClass).
You never cast primitives to objects in java.

No, you cannot cast this. However, you can achieve a similar effect if you create a constructor for MyClass which accepts an integer as input. So something like:
public MyClass(int x) {
// do stuff to convert as you see fit here
}
then when using it, you do:
getRow = new MyClass( getListAdapter().getCount());

Related

How do I retrieve the Object type that I placed into a DefaultListModel?

I hope I explained what I'm after here well enough. I'm having trouble retrieving an Object type that I've placed into a DefaultListModel.
public class HiddenIntegerFieldListItem {
private final String displayedField;
private final int hiddenField;
public HiddenIntegerFieldListItem( String dField, int hField ) {
displayedField = dField;
hiddenField = hField;
}
public String getDisplayedField() { return displayedField; }
public int getHiddenField() { return hiddenField; }
#Override
public String toString() { return displayedField; }
}
... elsewhere ...
DefaultListModel listModel = new DefaultListModel();
listModel.addElement( new HiddenIntegerFieldListItem( "The String", 4) );
jList.setModel( listModel );
And here's the problem, when I go to retrieve it, it tells me it can't convert this to a String.
But I put in an Object ... so why isn't it returning me my Object?
The compiler is fine with everything ... up until I go to get my Object out of the model.
It gives me an incompatible type warning, looking for a String only when I do the following ...
HiddenIntegerFieldListItem hif =
(HiddenIntegerFieldListItem) jList.getModel().getElementAt( 0 );
What am I missing about this? Why does it only want to give me a String back and not my Object?
It certainly accepted the Object, and the Object has a toString() method in it. And all I get is ...
incompatible types: String cannot be converted to HiddenIntegerFieldListItem
I'm stumped. Ready to give up on storing a primary key along with the item description in a list box and write a whole bunch of spaghetti code instead, which seems silly. :D Anybody see what I'm trying to do here and know what I'm doing wrong? Can't models store Objects anymore? Only Strings?
In general at compile time when you pull items out of a data structure it doesn't look at what the type it was when you put in (e.g. what it actually is), what it's looking for is the signature of that method.
And if the method signature of the get method on your data structure returns an Object, then as far as the compiler is concerned everything that you pull out of the data structure is an Object.
Now you know that the actual class is a HiddenIntegerFieldListItem - so what you need to do is to tell the compiler that that's what it is, by casting it to that type before using it.
(And if you cast it to the wrong type the compiler will let you - and then you'll get a dummy-spit at runtime.)
To make sure that you don't cast something to the wrong type you can use the instanceof operator.
The other thing to note is that by casting something you're not changing what it fundamentally is, you're changing its appearance to the rest of the code. So the interface or definition of Object has certain methods, but the interface or definition of HiddenIntegerFieldListItem has different methods, but all the Object methods are still available.
So here Object represents a certain minimal functionality, and then when you cast it you're saying it has more functionality than that, and you can legitimately cast it to anything in its super-class hierarchy. But you can't cast it to a subclass of its actual class, because that subclass might have data and methods which your object actually doesn't have.
Ok, mock up worked. The problem was the netbeans designer had typed the JList for me, for Strings, when I didn't know it was going to do that automagically. Once I removed that from the type parameters input in the designer tool, all was well. But here was the mock up, for anyone else wanting to store a key beside the visible string in a JList.
public class Test {
class HiddenIntegerFieldListItem {
private final String displayedField;
private final int hiddenField;
public HiddenIntegerFieldListItem( String dField, int hField ) {
displayedField = dField;
hiddenField = hField;
}
public String getDisplayedField() { return displayedField; }
public int getHiddenField() { return hiddenField; }
#Override
public String toString() { return displayedField; }
}
public void tryIt() {
javax.swing.JList<HiddenIntegerFieldListItem> jList = new javax.swing.JList<>();
javax.swing.DefaultListModel listModel = new javax.swing.DefaultListModel();
listModel.addElement( new HiddenIntegerFieldListItem( "The String", 4) );
jList.setModel( listModel );
// all good up till there, then ... oh wait, it worked now! ???
HiddenIntegerFieldListItem hif = jList.getModel().getElementAt( 0 );
System.out.println( hif.getHiddenField() + "" ); //Yay! It works! Output: 4
}
public static void main (String args[] ) {
Test t = new Test();
t.tryIt();
}
}

Why does this print exception?

String bob2 = "3";
System.out.println((int)bob2);
I'm unsure of why this causes an exception. Can anyone explain? Pretty sure because of the int on String type, but want to make sure.
Yes you are right its because of typecasting. If u need to convert String to int use below code
Integer.parseInt("3");
You are correct.
You can't just cast a string to an int.
You should convert it using Integer.parseInt()
Use this
Integer.valueOf("3");
or
Integer.parseInt("3");
In Java whenever you are trying to change type of an entity to another, both the types should have some relation. Like if you are trying to caste a sub class object to super class, it will work smoothly. But if you try to compare a Person object with a Lion object, that comparison is meaning less, the same is the logic in casting. We cannot cast a Person object to Lion object.
In your code bob is String type and you are trying to cast it to int and in Java both String and Integer is not having any relation. That's why Java is throwing Exception, Class Cast Exception I guess, this is raised when different types of objects are compared.
But the parseInt(String arg) method in Integer class gives an option to convert numeric String to Integer, given that the argument is a qualified Integer as per Java standards.
Example :-
String numericString = "1234";
int numberConverted = Integer.parseInt(numericString);
System.out.println(numberConverted);
You can also try these which will tell you the precautions before using this method
int numberConverted = Integer.parseInt("1234r");
int numberConverted = Integer.parseInt("1234.56");
int numberConverted = Integer.parseInt("11111111111111111111111111111");
You can't cast String to Integer. Change:
System.out.println((int)bob2);
to:
System.out.println(Integer.parseInt(bob2));
It will create an Integer value from the String provided with bob2 variable. You can also create a reference to int variable like this if you want to store primitive int instead of Integer:
int intBob2 = Integer.parseInt(bob2);

Java Cast from Object to long to String

Here's the situation, I have an Object in a Map which I explicitly know to contain an instance of Long and I need to turn that value into a string but keep getting incompatible type errors. Here's what my code looks like:
Map<String, Object> map = ...;
Object obj = new Long(31415L);
String str = Long.valueOf((long)map.get("id")); //Problem line
This gives:
Inconvertible types.
Found : java.lang.Object
Required: long
Any suggestions as to how to get around this?
You can just do
String str = map.get("id").toString();
Use, for instance:
String.valueOf(map.get("id"))
The problem is that you try and cast an object to a primitive type. That cannot work.
But since the values of your map will be Longs anyway (collections cannot contain primitive types, save for specialized implementations such as found in GNU Trove), look at #BheshGurung's answer...
You can use the toString function;
public String toString() {
return String.valueOf(map.get("id"))
}
String str = map.get("id").toString();
You have 2 issues here:
You created a *L*ong, not a *l*ong. Therefore you need to cast back to a *L*ong, not a *l*ong.
In order to get the String representation of a *L*ong you must call toString() on it.
Use this:
String str = ((Long)map.get("id")).toString();

Get index of enum from string?

I have a string value, I also have an array of strings and an enum containing the range also.
To get the index of the string in the array, from the value supplied I write this:
Arrays.asList(myClass.BAUD_RATES).indexOf(username)
How do I do this for an enum? Can I use ordinal? Or do i have to make my own method?
The method might go like:
public enum Fruit {
...
static public boolean isMember(String aName) {
Fruit[] aFruits = Fruit.values();
for (Fruit aFruit : aFruits)
if (aFruit.fruitname.equals(aName))
return aFruit;
return false;
}
...
}
Not sure if I understand you correctly but based on question title you may be looking for
YourEnum.valueOf("VALUE").ordinal();
//like Directions.valueOf("NORTH").ordinal();
YourEnum.valueOf("VALUE") returns enum value with name "VALUE"
each enum value knows its position (indexed from zero) which we can get by calling ordinal() method on it.
I might not understand you question, but the same code works for enums too:
int index = Arrays.asList(YourEnum.values()).indexOf(YourEnum.ENUM_ITEM);
Or you can get:
int index = YourEnum.valueOf("ENUM_ITEM").ordinal();
Try this simple solution:
Fruit.values()[index]
If you want to retrieve the index, you can use ordinal. If you want to assign some specific value to String, you may define your own method to retrieve it.
enum DAY
{
MONDAY(10),
TUESDAY(20);
int value;
DAY(int x)
{
this.value = x;
}
public int getValue()
{
return value;
}
Now value and ordinal can be retrieved as :
for(DAY s : DAY.values() )
{
System.out.println(s.ordinal());
System.out.println(s.getValue());
}
The following logic will also work.
If you want to check and you know the fruitname already don't use for loop go with the approach mentioned by Pshemo
for (Fruit aFruit : aFruits)
if (aFruit.name().equals(aName))
return aFruit.ordinal();
Adding here the solution that worked for me:
YourEnum.values.indexOf("VALUE");

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.
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.
How can I fix that?
Integer.parseInt()
expects a String. You can use
Integer.parseInt(f.toString())
and override the toString() method in your class.
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. 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());

Categories