java


Java How to tell which Object is in a HashMap


I have a HashMap:
HashMap<String, anObjectClass> myHash = new HashMap<String, anObjectClass>();
I have my anObjectClass:
public class anObjectClass {
private String name;
private ArrayList<String> myObjectList = new ArrayList<String>();
}
I have another class that extends my anObjectClass that adds another String:
public class secondObjectClass extends anObjectClass {
String quote;
}
Which means I have two kinds of objects within my HashMap:
My anObjectClass objects which have a String name and an ArrayList of Strings: myObjectList
And my secondObjectClass objects which adds another String: quote.
My question is, if I have a String key, say "ABC". I know I can tell whether or not there is a key "ABC" in my HashMap with the containsKey() method. But once I have found a key "ABC", how do I tell if it is an anObjectClass object or a secondObjectClass object? In other words, how can I tell what kind of object matches with that key? Thank you in advance.
You can use the keyword instanceof to determine the types of different objects in Java.
In your example, say you are trying to determine the type of an object obj that is either an instance of anObjectClass or secondObjectClass. You can tell the type by using the following code:
if(obj instanceof secondObjectClass) {
// obj is of type secondObjectClass
} else if(obj instanceof anObjectClass) {
// obj is of type anObjectClass
}
This is fine, but beware - types are transitive. That is, an instance of secondObjectClass is also of type anObjectClass because it is a subclass of it. It is therefore helpful to be as specific as possible when using instanceof.
For objects for which you control the definitions, define a boolean
boolean isBaseClass() { return(true); }
and in the subclass define
boolean isBaseClass() { return(false): }
but more generally, use method inheritance instead of this kind of test,
because it can be extended to any family of classes.
// bad
if(x.isBaseClass()) { doThis(); } else { doThat(); }
// better
x.doNextThing()
You can also use isAssignableFrom method of Class class.
So your code will look like
if(obj.getClass().isAssignableFrom(BaseClass.class)) {
//bla
}
if(obj.getClass().isAssignableFrom(SuperClass.class)) {
//blabla
}
I like this because I don't have to worry about the order of if else's nor do I need to write nested if elses.
EDIT
By order I meant while using instanceof, your if elses have to be placed in a way that the sub class is checked before the base class instanceof check. Sorry for causing any confusion. Thanks #EJP for pointing out.

Related Links

Remote debug java integration test on Jenkins
We know we cant create object of interface but then how do we create object of Statement or PrepareStatement in jdbc? [closed]
Asterisk shared data between two channels in a call
Setting Image on the JTextField in Swing Java Netbeans
how to create a new database in sqlite? we have to use sqlite because we are making an android application.
ArcGIS API calls with Android
Using JAVA API update Rally Team membership
Can't see any data in h2 database
Interrupt in java thread
ArrayIndexOutOfBoundException on calling View.draw(Canvas) method
Android: Downloading from URL
Session timeout not happening
Writing a 2D Array to a string, then to a .txt file - Java
JavaFX changing header of titled pane icon
After searching a hashmap, how do I have it highlight result in jlist?
Android UDP needs to recover from back packets

Categories

HOME
maven
testing
azure-data-factory
reserved
relative-path
relay
jira
frameworks
binary-tree
win32gui
maude-system
windows-10-universal
handsontable
apache-cayenne
jplayer
usergrid
quickfix
systemc
after-effects
progressive-web-apps
tostring
fatal-error
sms-gateway
shared-hosting
jquery-ajaxq
web-sql
sylius
p-value
entitlements
fifo
libssl
quote
gsmcomm
librato
gsoap
phonegap
functor
accelerate-framework
io-redirection
simplexml
withings
webix-treetable
streamreader
sfdc
keydown
s
executenonquery
skeleton-css-boilerplate
atomicity
multipeer-connectivity
clean-architecture
rdfs
git-diff
tropo
darcs
knockout-components
magma
dtexec
knpmenubundle
chord-diagram
crosswalk-runtime
color-picker
removechild
ado.net-entity-data-model
paypal-express
plottable.js
pagedlist
skype4py
hill-climbing
python-stackless
ipconfig
iad
t4mvc
jmeter-maven-plugin
fouc
tableau-online
splash
sankey-diagram
createprocessasuser
sonarqube5.1.2
dereference
geonetwork
rake-task
operator-precedence
camanjs
codeigniter-url
knuth
phalanger
websocket4net
php-5.4
sgen
valuechangelistener
android-2.2-froyo
oracle-warehouse-builder
mcts
prettify
terminal-services
multiprocessor
ms-project-server-2010
rabl
pushbackinputstream
android-screen-support
rdoc
cisco-jtapi
bluepill
gdata-api
datawindow
amazon-appstore
gwt-ext
window-management
xmemcached
yui-datatable
datareader
asp.net-mvc-areas
perfect-hash
webkit.net
signal-handling
ajax-forms

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App