How to declare the put method of Hash Table? - hashtable

I donĀ“t know how to resolve this error about the declaration of put method...
private Hashtable<Acronimo, Acronimo> lista;
public Dicionario() {
lista = new Hashtable<Acronimo, Acronimo>();
}
//adiciona
public boolean juntaAcronimo(Acronimo aAcronimo) {
if( lista != null) {
return lista.put(aAcronimo.getChave(), aAcronimo);
}
return false;
}
The method put(Acronimo, Acronimo) in the type Hashtable is not applicable for the arguments (String, Acronimo)

You have used invalid generic type in the lista field declaration, it should be:
private Hashtable<String, Acronimo> lista;
Consider using a HashMap instead of Hashtable. Hashtable is an old class from early Java version and due to backward compatibility it's needlessly synchronized.
private Map<String, Acronimo> lista = new HashMap<>();

Method aAcronimo.getChave() returns String while you defined your hashtable as <Acronimo, Acronimo> so all you have to do is to change this:
private Hashtable<String, Acronimo> lista;

Related

Sorting a list with Objects and A primitive String

I am trying to sort a list as given below.
List dg = new ArrayList();
dg.add(new Dog("one"));
dg.add(new Dog("two"));
dg.add(new Dog("three"));
dg.add(new Dog("four"));
dg.add(new String("Ankit"));
I have tried to implement comparable for Dog class below (not sure if it is useful here)
//Dog class below//
class Dog implements Comparable<Dog>{
String name;
public Dog(String name) {
this.name = name;
}
public String getName() {
return name;
}
public int compareTo(Dog d){
return this.getName().compareTo(d.getName());
}
The issue is however I write the comparator as given below I get ClassCastException. How to solve this?
class StringComparator implements Comparator {
public int compare(Object d, Object s) {
String p=((Dog)d).getName();
return (p.compareTo(s.toString()));
}
}
//usage of the above comparator
Arrays.sort(odog,sc);
Issue is:
See that to a list you are mixing String object with Dog objects using dg.add(new String("Ankit")); Do you really need string object.
Then you try to sort it using your comparator and your comparator blindly type cast values to Dog object. So when it encounters your String object it tries to type cast it to String object which is not possible (due to Dog not a subclass of String) and hence you get ClassCastException.
I would remove String object from Dog list to resolve the issue.

c# json.net custom serialization of subobjects

I am using JSON.NET to serialize a class to JSON. The class contains a property which consists of a list of items, and I want to serialize the items themselves in a custom way (by dynamically including only certain properties, using a customized ContractResolver). So basically I want to serialize the parent class itself in a standard way, with the DefaultContractResolver, but serialize this one property in a custom way, with my own ContractResolver.
JSON.NET has methods that probably allow this but the documentation is rather sketchy. Any help would be appreciated.
I solved this problem with a ContractResolver. The list of objects that I want to serialize is heterogeneous, so I have to pass it two arguments, a list of properties to be serialized, and a list of types to which the property list applies. So it looks like this:
public class DynamicContractResolver : DefaultContractResolver
{
private List<string> mPropertiesToSerialize = null;
private List<string> mItemTypeNames = new List<string>();
public DynamicContractResolver( List<string> propertiesToSerialize,
List<string> itemTypeNames )
{
this.mPropertiesToSerialize = propertiesToSerialize;
this.mItemTypeNames = itemTypeNames;
}
protected override IList<JsonProperty> CreateProperties( Type type, MemberSerialization memberSerialization )
{
IList<JsonProperty> properties = base.CreateProperties( type, memberSerialization );
if( this.mItemTypeNames.Contains( type.Name ) )
properties = properties.Where( p => mPropertiesToSerialize.Contains( p.PropertyName ) ).ToList();
return properties;
}
}
And it is called like this:
DynamicContractResolver contractResolver = new DynamicContractResolver( propsToSerialize, GetItemTypeNames() );
json = JsonConvert.SerializeObject( this, Formatting.None,
new JsonSerializerSettings { ContractResolver = contractResolver } );
where GetItemTypeNames() calls GetType().Name on each of the items in the list that I want to serialize and writes them distinctly to a list.
Sorry my original question was vague and badly phrased, and if somebody has a better solution I am certainly not wedded to this one.
Here's a version that's a bit better. It associates type names with properties, so you can specify which properties you wish to have serialized at every level. The keys to the dictionary are type names; the value is a list of properties to be serialized for each type.
class PropertyContractResolver : DefaultContractResolver
{
public PropertyContractResolver( Dictionary<string, IEnumerable<string>> propsByType )
{
PropertiesByType = propsByType;
}
protected override IList<JsonProperty> CreateProperties( Type type, MemberSerialization memberSerialization )
{
IList<JsonProperty> properties = base.CreateProperties( type, memberSerialization );
if( this.PropertiesByType.ContainsKey( type.Name ) )
{
IEnumerable<string> propsToSerialize = this.PropertiesByType[ type.Name ];
properties = properties.Where( p => propsToSerialize.Contains( p.PropertyName ) ).ToList();
}
return properties;
}
private Dictionary<string, IEnumerable<string>> PropertiesByType
{
get;
set;
}
}

How do you make a class method modify itself?

asp.net C#4
I have a simple class to working with query strings.
A new instance is created like this:
public QueryString(string querystring)
{
try
{
_table = new Hashtable();
if (querystring.Length > 0)
{
foreach (string pair in querystring.Split('&'))
{
string[] item = pair.Split('=');
_table.Add(item[0].ToLower(), item[1]);
}
}
}
catch (Exception)
{
}
}
I want to add a method to this that will remove a key value pair. I don't want it to return a new querystring, I just want it to remove the pair from the current instance. Not sure how to do that since it says I can't assign a value to 'this'
public void Remove(string key)
{
String querystring = this.ToString();
try
{
_table = new Hashtable();
if (key.Length > 0)
{
foreach (string pair in querystring.Split('&'))
{
string[] item = pair.Split('=');
if (item[0] != key)
{
_table.Add(item[0].ToLower(), item[1]);
}
}
this = _table;
}
}
catch (Exception)
{
}
}
You're overcomplicating things. Since your class's state is made up of the _table field, all you need to do is remove the item with the given key from that field.
The following example replaces your untyped Hashtable wit a strongly-typed Dictionary. I also chose to initialize the dictionary with a LINQ statement, but you could keep your old code there if you prefer.
public class QueryString
{
private readonly Dictionary<string, string> _table;
public QueryString(string querystring)
{
if (querystring.Length > 0)
{
var pairs =
from pair in querystring.Split('&')
let item = pair.Split('=')
select new {key = item[0], value = item[1]};
_table = pairs.ToDictionary(p => p.key, p => p.value);
}
}
public void Remove(string key)
{
_table.Remove(key);
}
}
You cannot assign a value to this since it is a reference to the object itself.
However, if you remove the line this = _table; , isn't things working as they should then? I guess your ToString() is somewhat using the hashtable to generate a "printer friendly" QueryString, and if that is the case, the way I see it, your Remove() method should be working (since you are replacing the _table variable with a new HashTable not including the key-value pair you want to exclude).
you are passing a querystring into the class so the original querystring IS intact.
However you then break down the querystring into a a Hashtable of key/value pairs. If you want to keep THAT intact you need to clone the HashTable and perform the remove on the clone.
In any case it's probably a good idea to keep the querystring you are passing in as a constructor parameter in a member variable for safe keeping.

Using HQL to query on a Map's Values

Let's say I have a map (call it myClass.mapElem<Object, Object>) like so:
Key Val
A X
B Y
C X
I want to write HQL that can query the Values such that I can get back all instances of myClass where mapElem's value is 'X' (where 'X' is a fully populated object-- I just don't want to go through each element and say x.e1 = mapElem.e1 and x.e2=... etc). I know I can do this for the keys by using where ? in index(myClass.mapElem), I just need the corresponding statement for querying the values!
Thanks in advance...
ETA: Not sure if the syntax makes a difference, but the way I am actually querying this is like so:
select myClass.something from myClass mc join myClass.mapElem me where...
You should use elements(). I tried simulating your example with the following class
#Entity
#Table(name="Dummy")
public class TestClass {
private Integer id;
private Map<String, String> myMap;
#Id
#Column(name="DummyId")
#GeneratedValue(generator="native")
#GenericGenerator(name="native", strategy = "native")
public Integer getId() {
return id;
}
#ElementCollection
public Map<String, String> getMyMap() {
return myMap;
}
public void setId(Integer id) {
this.id = id;
}
public void setMyMap(Map<String, String> myMap) {
this.myMap = myMap;
}
}
And persisted a few instances, which constain maps of a similar structure to what you have in your example. (using < String, String > since the values in your example are strings)
The following query gives me all instances of TestClass, where the map contains a specific value
SELECT DISTINCT myClass
FROM TestClass myClass JOIN myClass.myMap myMap
WHERE ? in elements(myMap)
In my particular case, I ended up having to use an SQL query. Not ideal, but it worked.

How can I check if a class belongs to Java JDK

I use an external library which return some List<?>.
I need to check if each object of this list is an Object of the JDK (String, int, Integer...).
Is this a proper solution?
List<?> list = externalLibrary.search(...);
for(clazz : list) {
if (clazz.getPackage().getName().startsWith("java.lang"))
// do something different
}
Is there a better one?
Depending on your definition of "object of the JDK" -- which could get quite fuzzy around the edges -- no, this isn't going to do it. The java.lang package is only a tiny part of all the classes included in the JDK.
You might check whether each object was loaded by the same ClassLoader that loaded java.lang.String -- i.e.,
if (theObject.getClass().getClassLoader() == "".getClass().getClassLoader()) ...
In general, a different ClassLoader will be used for system classes vs. application classes.
It is probably OK, just you have to check the following packages:
java
javax
com.sun
sun
probably others...
We use the below class to check if the classes belongs to JDK
public class JDKClass {
private static Set<String> CS = new HashSet<String>();
static {
try {
File file = new File(System.getProperty("java.home"),
"lib/classlist");
BufferedReader r = new BufferedReader(new FileReader(file));
String l;
while (true) {
l = r.readLine();
if (l == null) {
break;
} else {
CS.add(l.replace('/', '.'));
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static boolean contains(String o) {
return CS.contains(o) || o.startsWith("java") || o.startsWith("com.sun")
|| o.startsWith("sun") || o.startsWith("oracle")
|| o.startsWith("org.xml") || o.startsWith("com.oracle");
}
private JDKClass() {
}
}
You can use ClassLoader.getSystemResources and then check from what jar is the class loaded (f.g. if it comes from rt.jar).
You will get URL's such as:
jar:file:/C:/Users/user/.m2/repository/org/slf4j/slf4j-log4j12/1.6.1/slf4j-log4j12-1.6.1.jar!/org/slf4j/impl/StaticLoggerBinder.class
Example code taken from SLF4j:
private static String STATIC_LOGGER_BINDER_PATH =
"org/slf4j/impl/StaticLoggerBinder.class";
private static void singleImplementationSanityCheck() {
try {
ClassLoader loggerFactoryClassLoader = LoggerFactory.class
.getClassLoader();
Enumeration paths;
if (loggerFactoryClassLoader == null) {
paths = ClassLoader.getSystemResources(STATIC_LOGGER_BINDER_PATH);
} else {
paths = loggerFactoryClassLoader
.getResources(STATIC_LOGGER_BINDER_PATH);
}
List implementationList = new ArrayList();
while (paths.hasMoreElements()) {
URL path = (URL) paths.nextElement();
implementationList.add(path);
}
....
}
Personally I like class loader base answer. But it will return true also on StringBuilder. If you want to more narrow definition that is only "built-in" types, you can try to evaluate whether this is primitive type (such as int) or wrapper type (such as Integer) or String. You can write something like this:
import java.util.Map;
import java.util.TreeMap;
public class Utils {
private static Map<String, Class<?>> SUBST_MAP = new TreeMap<String, Class<?>>();
private static Map<String, Class<?>> SIMPLE_MAP = new TreeMap<String, Class<?>>();
static {
SUBST_MAP.put(Byte.class.getName(), Byte.TYPE);
SUBST_MAP.put(Short.class.getName(), Short.TYPE);
SUBST_MAP.put(Integer.class.getName(), Integer.TYPE);
SUBST_MAP.put(Long.class.getName(), Long.TYPE);
SUBST_MAP.put(Float.class.getName(), Float.TYPE);
SUBST_MAP.put(Double.class.getName(), Double.TYPE);
SUBST_MAP.put(Boolean.class.getName(), Boolean.TYPE);
SUBST_MAP.put(Character.class.getName(), Character.TYPE);
SIMPLE_MAP.put(String.class.getName(), Boolean.TRUE);
}
/**
* Gets the the class type of the types of the argument.
*
* if substPrimitiveWrapper is true,
* then if there is argument, that represent primitive type wrapper (such as Integer),
* then it will be substituted to primitive type (such as int).
* else no substitution will be done.
*
* #param arg object.
* #param substPrimitiveWrapper - wheteher to do primitive type substitution.
* #retrun class type.
*/
public static Class<?> getClassType(Object arg, boolean substPrimitiveWrapper){
Class<?> classType = null;
String className = null;
Class<?> substClass = null;
if(arg != null ){
//making default classType
classType = arg.getClass();
if(substPrimitiveWrapper){
className = classType.getName();
substClass = (Class<?>)SUBST_MAP.get(className);
if(substClass != null){
classType = substClass;
}
}
}
return classType;
}
/**
* This method consider JDK type any primitive type, wrapper class or String.
*
*
* #param arg object
* #return where arg is JDK type or now.
*/
public static boolean isJDKClass(Object arg){
Class<?> classType = getClassType(arg, true);
boolean isJDKClass = false;
if(classType!=null){
//if(String.class.equals(classType)){
// isJDKClass = true; //this is String, note that String is final
//}
assert classType!=null;
String className = classType.getName();
Boolean isFound = (Boolean)SIMPLE_MAP.get(className);
if(Boolean.TRUE.equals(isFound)){
isJDKClass = true; //this is predefined class
}
boolean isPrimitiveType = classType.isPrimitive();
if(isPrimitiveType){
isJDKClass = true; //this is primitive type or wrapper class
}
}
return isJDKClass;
}
}
You can also optionally add support for such classes like java.math.BigDecimal, java.util.Date, java.sql.Timestamp. Note, however, that they are not final, so I assumed that if somebody extended them even in the trivial way, it will not be considered as JDK class.
I think an easier solution is to thing of the problem this way:
write a method to identify all classes that are defined by you. In most cases, all user defined classes follow a pattern like com.something.something. Then if they do not belong to com.something.something, it is a JDK class

Resources