Click to See Complete Forum and Search --> : ArrayList or Object assignment?
NOMADMAN
Feb 23rd, 2003, 07:40 PM
I have class edge:
public class GraphMap
{
private ArrayList _vertices;
// ... deleted most of class, only important stuff...
public void addEdge( int start, int end, double dist )
{
Vertex tempVert = new Vertex();
tempVert = _vertices.get( start );
}
This gives me the compiler error:
Incompatible type for =. Can't convert Object to Vertex.
tempVert = _vertices.get( start );
Why is this happening and can I get around it? Does using ArrayLists limit me to added classes that inherit Object class? Can I write an assignment operator for my Vertex class, if so what would a sample declaration line look like?
NOMAD
crptcblade
Feb 23rd, 2003, 09:17 PM
Everything in Java inherits from Object by default. To make your code work, you simply need to cast the Object to your object type.
public void addEdge( int start, int end, double dist )
{
Vertex tempVert = (Vertex)_vertices.get( start );
}
That should work.
NOMADMAN
Feb 23rd, 2003, 10:23 PM
Thanks worked like a charm.
Another question: I made a few classes that use each other.
Like a node class and a tree class. They are in different files, how can I #include them in my java program?
I have package BSTree written at the top of all of them. Is that correct?
(If you noticed my #include I'm native more to C++/C, how is the include macro done in Java?
Thanks!
NOMAD
crptcblade
Feb 23rd, 2003, 10:34 PM
The import keyword is what you're looking for. At the top of your code.
import java.util.*;
Imports the entire jave.util package.
import java.util.Hashtable;
imports just the Hashtable class.
All import does is save you typing. Without using import, you would have to declare a Hashtable like this :
java.util.Hashtable ht = new java.util.Hashtable();
:)
NOMADMAN
Feb 23rd, 2003, 10:58 PM
so if I imported a class that I made it would be
import Tree
?
NoMaD
Dillinger4
Feb 23rd, 2003, 11:55 PM
If the class that you wish in import is in the current directory then no import statement should be needed. But if the class is defined in a directory other then what is defined in the classpath environment variable then i am pretty sure that an import statement would be needed. I never did get packages and imports to work right so i might be wrong on this. :D
CornedBee
Feb 24th, 2003, 06:02 AM
Not entirely correct. You don't need an import if the class you're using is in the same package. You always need an import if it's in a different package.
And the files must always be in the CLASSPATH or in the same directory, independent from any imports.
Look at the java docs to find out how the JRE resolves class file locations.
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.