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

First line data of second page onwords distorted in Pdf generation by using com.lowagie.text.pdf with java?
How to add formula for the column in excel sheet to have unique values and remove duplicates
objectInputStream.readObject() throws exception java.io.OptionalDataException
Where is the port number defined, which is used in JDBC hive connection string?
Is there any option to automate APIs using Java and Selenium webdriver
Access data from the URL to java using thymeleaf?
Select DISTINCT on JPA
Spring #Component #Autowired
If condition is skipped what is wrong with this code?
Error injecting remote EJB into Spring
Error java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first
Using different projection for each entity subtype
java.lang.NoClassDefFoundError: Could not initialize class me.gacl.util.JdbcUtils [duplicate]
JPA query database to update a memory collection
Android: SQLite error in adding data
Fetch contacts from google contact api java

Categories

HOME
comparison
iot
relay
bpmn
kalman-filter
jira
sharepoint-designer
portia
webrequest
basic
metatrader4
vault
export-to-csv
resize
phaser
uitypeeditor
systemc
jsdoc
pugjs
immutable.js
reverse-proxy
physics-engine
firebase-crash-reporting
crystal-reports-2010
sqlcipher
semantic-analysis
intel-pin
nhapi
windows-error-reporting
vision
file-rename
binary-data
ioio
http-get
ghost4j
android-ble
reportbuilder
ansible-playbook
angularjs-factory
tasker
dynamic-reports
btrace
cubic-spline
osx-mavericks
pubmed
jlink
dropbox-php
forever
iso8601
angular-strap
nested-sets
setuptools
intrusion-detection
storekit
jwplayer7
hill-climbing
oauth2client
associative-array
photobucket
javax.sound.midi
msys
collapse
comobject
ruby-2.2
dukescript
responsive-images
sankey-diagram
mdt
fpml
applescript-objc
onactivityresult
php-5.4
page-layout
quantlib-swig
runtime.exec
odata4j
cisco-jtapi
bluepill
libc++
nsobject
android-sdk-2.1
lpeg
site.master
paster
libs
backcolor
phonon
sector
gacutil
scripting-languages
commodore

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