Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt on Arrays

 
sukhavasi vasavi
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public static void main(String[] args) {

Object[] oa = new Object[3];

oa[0] = new Integer(1);

int i = oa[0];//3

System.out.print(i);
}
}

Why this prog shows compilation error at line 3?
While I replaced Object with int it is working .Plese Explain?
 
Srinivasan thoyyeti
Ranch Hand
Posts: 557
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
vasavi,

Object[] oa = new Object[3];

oa[0] = new Integer(1);

// we can't assaign Object to primitive without casting.
if (you are using 1.5) {
int i= (integer)oa[0];
else{
int i= ((integer)oa[0]).intValue();
}
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Howdy ranchers,

in a more general view, this does not have necessarily anything to do with arrays.
More with the topic Polymorphism. When you have a polymorph variable e.g.
Object variable = new Integer(42);

Then variable is of type Object and you can perform only Object methods on it (for example hashCode() or toString());
You can never do any integer things with variable. Because a variable has a fixed type that can never changed.
But you can set up a second variable of type Integer, and refer this new variable to the Integer object (object as object, not as class Object!):
Integer i = (Integer) variable;
System.out.print(i/6);

ok, the last line requires autoboxing and won't do in java 1.4


This general issue is the base of your array question.


Hope this cleares something.

The cause why Srinivasan's code does not compile is the fact that java is CaSe sEnsItiVE.


Bu.
 
Srinivasan thoyyeti
Ranch Hand
Posts: 557
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Burkhard,

Eagle eyes .
I didn't compile that.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic