Casting in java && wrapper class

  • Context: Comp Sci 
  • Thread starter Thread starter the_kool_guy
  • Start date Start date
  • Tags Tags
    Casting Class Java
Click For Summary

Discussion Overview

The discussion revolves around the use of the Vector and ArrayList classes in Java, particularly focusing on type specification, object storage, and retrieval of values from wrapper classes. Participants explore the implications of using different data types within these collections and the mechanics of accessing stored values.

Discussion Character

  • Technical explanation
  • Conceptual clarification
  • Debate/contested
  • Homework-related

Main Points Raised

  • One participant asks whether a Vector must have a specific data type for its elements, suggesting that any object can be stored in it.
  • Another participant asserts that while any object can be stored in a Vector, it is deprecated and recommends using ArrayList instead, explaining the benefits of type specification.
  • There is a discussion about how to retrieve an int value from an Integer stored in a Vector, with options presented for direct access versus using the intValue method.
  • A participant questions the implications of storing a non-Employee reference in a list specified for Employees, asking about the feasibility of retrieving such an object after casting.
  • Another participant emphasizes the risks of mixing different object types in a list and suggests using the Object class if necessary, while cautioning against the potential for class cast exceptions.
  • Clarification is sought regarding the syntax of the enhanced for loop, with explanations provided about its functionality compared to traditional for loops.

Areas of Agreement / Disagreement

Participants express differing views on the use of Vector versus ArrayList, with some advocating for ArrayList due to its type safety and others discussing the flexibility of using Vector. There is no consensus on the best practices for storing mixed types in collections, as opinions vary on the implications and risks involved.

Contextual Notes

Participants note that using a Vector is not recommended due to its deprecation, and there are concerns about type safety when mixing different object types in collections. The discussion includes various assumptions about object casting and retrieval methods that remain unresolved.

Who May Find This Useful

This discussion may be useful for Java programmers, particularly those interested in data structures, type safety, and object-oriented programming concepts.

the_kool_guy
Messages
37
Reaction score
0
casting in java...&& wrapper class

Homework Statement



well my question is quite simple.
1..) when a vector is instantiated ,does it needs to have a particular data type like integer,employee... like in case of array or does any object can be put into it irrespective of its name...
example.
Vector employee = new Vector(50,20);
can i store a reference to integer by wrapping it in this vector

2..) when a Integer class is stored in vector,how can i get the int value stored in it.
a.. just by accessing the index where a wrapper class is stored .. or..
b.. storing the accessed reference in some variable and then applying Intvalue method..?

second question pls clarify w.r.t every other primitive wrapper class...

thanks

Homework Equations


The Attempt at a Solution

 
Physics news on Phys.org


the_kool_guy said:

Homework Statement



well my question is quite simple.
1..) when a vector is instantiated ,does it needs to have a particular data type like integer,employee... like in case of array or does any object can be put into it irrespective of its name...
example.
Vector employee = new Vector(50,20);
can i store a reference to integer by wrapping it in this vector
No, you can store any object in the vector, but you shouldn't be using the Vector class anyways, it's deprecated - use ArrayList.

You can specify what type of object the ArrayList will store like so:

ArrayList<Integer> al = new ArrayList<Integer>();

That means you don't have to cast elements in the ArrayList. For example, if you hadn't specified Integer, it would assume instances of Object. So you would have to do this to get element # 0, for example:

Integer int = (Integer)al.get(0);

Of course, if it finds a non-Integer in there, you'll get a cast exception.

Whereas you can't put non-Integers in there if you specified Integer. You could just get it out this way:

Integer i = al.get(0);

However, you can go between Integer and int types pretty transparently (autoboxing). This is also perfectly valid:

int i = al.get(0);

I'm glossing this over a bit, but that should give you an idea how it works.

the_kool_guy said:
2..) when a Integer class is stored in vector,how can i get the int value stored in it.
a.. just by accessing the index where a wrapper class is stored .. or..
b.. storing the accessed reference in some variable and then applying Intvalue method..?

second question pls clarify w.r.t every other primitive wrapper class...

Let me show you a quick snippet of code that should demonstrate how it works:

Code:
import java.util.ArrayList;

public class AL {
    public static void main(String[] args)
    {
        ArrayList<Integer> al = new ArrayList<Integer>();
        al.add(0);
        al.add(2);
        al.add(4);

        for (int i : al) {
            System.out.println(i);
        }

        int x = al.get(1);
        System.out.println(x);
    }
};

Notice how I took little note of the fact that the ArrayList contains Integer objects rather than int primitive types. Other primitive types are pretty much the same.

If you're using some kind of tutorial or whatever that uses Vector classes, I strongly suggest you find one that is even remotely up to date.

Hope that clears things up.
 


ok... what if i specified the data type like Employees and store a nonemployee reference like game in it..
then can i retrieve the game object reference after casting.?.
.
.
.
also i am not getting the (for) format used by you..can you please explain it...?
 


As Grep said, if you don't specify a type for the array list, you should be able to hold anything in that list. So suppose you have this (not recommended) code:

Code:
List list = new ArrayList();
list.add(new Game());
list.add(new Employee());

You should be able to say:
Code:
Game game = (Game) list.get(0);
Employee employee = (Employee) list.get(1);

However, make sure you cast it correctly, else, as Grep said, you'll get an class cast exception. Meaning, if you put more than one type of object in the list, you can't do this:

Code:
for (int i = 0; i < list.size(); i++){
     Employee employee = (Employee) list.get(0);
     ...do something with employee
}

As for the for loop, that is another way of going through the loop. It's the same as the code I had written above. So instead of writing the above for loop, I could write it like this:

Code:
for (Employee employee : list){
     ...do something with employee
}

But this only work if you declare list as an Employee list.

Code:
List<Employee> list = new ArrayList<Employee>();

I hope that makes some kind of sense.
 


the_kool_guy said:
ok... what if i specified the data type like Employees and store a nonemployee reference like game in it..
then can i retrieve the game object reference after casting.?.

Yes, though you should think hard before doing that. It's generally a bad idea to put objects of different classes with no common base class (other than Object) into the same list. Like in that case, I don't see what Employee and Game objects might have to do with each other, and why they'd be in the same list.

Since the base class of all objects in Java is the Object class, you can specify that the objects are of type Object. Though that's unnecessary. Just don't specify the class type and you can put anything in (and get anything back out). As I showed you:

ArrayList al = new ArrayList();

However, now you need to worry about what the type of each object in the list. You end up with stuff like (written directly here and not tested, just an example):
Code:
if (object instanceof Employee) {
    Employee emp = (Employee)al.get(index);
} else if (object instanceof Game) {
    Game game = (Game)al.get(index);
} else {
    // Unexpected object type! Good to handle such errors, but better to make sure they
    // can't happen in the first place.
}

Usually, when I get to that point, I ask myself what I did wrong.

the_kool_guy said:
also i am not getting the (for) format used by you..can you please explain it...?

That's the ranged for loop. It's a clear and concise way to iterate over just about anything element by element.

Take this piece of code, where employees is some kind of sequential list of elements:
Code:
for (Employee emp : employees) {
    System.out.println(emp);
}

It will go through every element in employees and assign each one in turn to the emp variable (of type Employee). Every element obviously needs to be of type Employee. It's a short version of:

Code:
for (int i = 0; i < employees.size(); ++i)
{
    Employee emp = employees.get(i);
    System.out.println(emp);
}

Of course, the ranged for doesn't have a loop index variable, so if you care what element you're at, you want the regular for loop.

Does that make it clear?
 


thanks everyone...
that was really informative
 

Similar threads

  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 2 ·
Replies
2
Views
4K
  • · Replies 2 ·
Replies
2
Views
7K
  • · Replies 11 ·
Replies
11
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 15 ·
Replies
15
Views
2K
  • · Replies 55 ·
2
Replies
55
Views
7K