I have the below code :
public final class SomeStaticClass {
private static Map<String, Map<String,String>> tMap;
private SomeStaticClass(){
//Private Constructor to avoid instance creation
}
//getter method here to retrieve the map.
public static void setMap(Map<String, Map<String,String>> map){
tMap = map;
}
}
I want to restrict the setMap method to be called only once,so that the tMap cannot be modified later.
The tMap will be set only once during application startup and will be access by multiple objects later.
public static void setMap(Map<String, Map<String,String>> map){
if (null == tMap) // This will make sure tMap initialized only once
tMap = map;
}
Related
I have a class with static variable
#Data
public final class Code {
private static Map<String, List<String>> codesForType = new HashMap<String, List<String>>() {{
put("code1", Arrays.asList("AVDF", "WREQ", "AWER"));
put("code2", Arrays.asList("SHYT", "DWEA", "XSSS", "AQWE"));
}};
public static List<String> getCodesByType(String type) {
return codesForType.get(type);
}
}
with following api
#GetMapping("/codes")
public Code getCodeForType() {
return new Code();
}
This is giving exception with message No converter found for return value of type: class com.model.Code.
Tried making the member as public but still has the same issue.
It works when I remove static keyword from private static Map<String, List<String>> codesForType
I could be missing a basic understanding of static keyword.
You don't need to create a new object as your methods are static.
you can simply do this :
#GetMapping("/codes")
public List<String> getCodeForType() {
// replace type with something you will receive in your request.
return Code.getCodesByType(type);
}
I create Details class and that class create Map object. and set getters setters.
setdatavalues class I set values to the setters
Then I try to get that values in getdatavalues class. by calling getters methord.
problem is I cannot get values in that getters. display empty array.
In getdatavalues calss I create mymap object and assign getMyMap() method and display the values
public class Details{
private Map<String, String> myMap = new LinkedHashMap<String, String>();
public Details() {
super();
}
public Map<String, String> getMyMap() {
return myMap;
}
public void setMyMap(Map<String, String> myMap) {
this.myMap = myMap;
}
}
public static void setdatavalues(){
LinkedHashMap<String, String> myMap=new LinkedHashMap<String, String>();
ArrayList<String> fields,values=new ArrayList<String>();
Details details= new Details();
|
|
fields=readNumbers();
values=readStrings();
for(int j=0;j<fields.size();j++)
{
myMap.put(fields.get(j),values.get(j));
}
details.setMyMap(myMap);
}
}
public static void getdatavalues(){
Details details= new Details();
//System.out.println(details.getMyMap().values());
Map<String,String> mymap = details.getMyMap();
System.out.println(mymap.values());
}
output
details that is set values is setdatavalues is thrown away and new empty details is used in getdatavalues. You must pass the Details object that is set data to where data in Details object is printed to print the data set.
Without using getter and setter method how to prevent modification access from child class if super class has protected Hashmap variable?
This Map is mutable (So i should be able to add the values from super class)So can't use UnmodifiableMap(its only applicable immutable collection object)
Class A
{
protected Map<Integer,Integer> m = new HashMap<Integer,Integer>();
A()
{
m.put(10,11)
m.put(11.12)
}
}
Class B extends A
{
B()
{
super.m.put(34,90) —— I don’t want to give access to child class to add
the value and child class and its only should able to get the values.
}
}
Make the map unmodifiable, and populate it in the construction of A.
class A {
protected final Map<Integer,Integer> m;
A() {
Map<Integer, Integer> tempMap = = new HashMap<>();
tempMap.put(10,11);
tempMap.put(11.12);
this.m = java.util.Collections.unmodifiableMap(tempMap);
}
}
If and when B attempts to modify the map, a ´UnsupportedOperationException´ will be thrown.
If you want A to be able to modify the map, then you'll need a different approach in which the map is private, and a protected getter returns an unmodifiable map.
class A {
private final Map<Integer,Integer> m = new HashMap<>();
A() {
m.put(10,11);
m.put(11.12);
// m remains modifiable within the context of A
}
protected Map<Integer, Integer> getMap() {
return java.util.Collections.unmodifiableMap(m);
}
}
EDIT
If you really don't want to use a getter but still have read-only access, you can use this approach.
class A {
private final Map<Integer,Integer> writableMap = new HashMap<>();
protected final Map<Integer,Integer> m = Collections.unmodifiableMap(writableMap);
A() {
writableMap.put(10,11);
writableMap.put(11.12);
}
}
Using this approach, only m is visible outside A, and is read-only. Within A, you can update writableMap and these changes will be visible in m
Here is a variant of what Steve Chaloner presented in his answer:
public class A {
private final Map<Integer, Integer> map = new HashMap<>();
protected final Map<Integer,Integer> m = Collections.unmodifiableMap(map);
public A() {
map.put(10, 11);
map.put(11, 12);
}
}
The private map is modifiable in the A class and changes will be reflected in the protected m whenever changes are made in map.
It is being used this way in Concurrency In Practice for example.
This should be the best solution Composition:
Implement a new Map and keep an internal private modifiable map like this:
class A {
private Map<Integer,Integer> m = new HashMap<>();
protected Map<Integer, Integer> map = new Map<>() {
//implement interface
public Integer put(Integer key, Integer value) {
throw new UnsupportedOperationException();
}
public Integer get(Object key) {
return m.get(key);
}
public void clear() {
throw new UnsupportedOperationException();
}
public boolean containsKey(Object key) {
return m.containsKey(key);
}
public boolean containsValue(Object value) {
return m.containsValue(value);
}
//
// ... And so on
//
// ... with all other methods
}
A() {
m.put(10,11)
m.put(11.12)
}
}
class B extends A {
B() {
super.map.put(34,90) // thorws exception
super.m.put(34,90) // inaccesible
}
}
All modifications are allowed in A via m but subclasses may only acces them by map that was succesfully blocked modifications.
I had a static class that contained several static variables:
public class A{
static {
}
public static final String param1= "paramVal1";
public static final String param2= "paramVal2";
}
I want to change the code, so that the variables will be in a map:
public class A{
static {
}
private static Map<String, String> params = new HashMap<String, String>() ;
public static void initParams() {
params.put("param1", paramVal1);
params.put("param2", paramVal2);
}
However, I already have many classes that call those public parameters, and I don't want to go to every class and change it. Is there any way to use some define function, that would cause java to return the map's value, when the parameter is called? i.e if someone calls A.param1, it would return params.get("param1")
A parameter in not as easy to use (and overwrite) than a method. So I think that short answer to your question is no. That's one of the reasons of getters and setters. But you can allways do the inverse, that is keep the old parameters for compatibility and use a map for newer uses :
public class A{
static {
param1 = "paramVal1";
param2 = "paramVal2";
params = new HashMap<String, String>;
params.put("param1", param1);
params.put("param2", param2);
// eventually other inits for params
}
public static final String param1= "paramVal1";
public static final String param2= "paramVal2";
public static Map<String, String params;
/* or better private static Map<String,String> params
and access via getter */
public static getParam(String name) {
return param.get(name);
}
}
That way, old classes could allways do A.param1, and for newer classes you could start using A.get("param1").
You can do this:
public class A {
private static Map<String, String> params = new HashMap<String, String>();
static {
params.put("param1", "paramVal1");
params.put("param2", "paramVal2");
}
public static final String param1 = params.get("param1");
public static final String param2 = params.get("param2");
}
I have multiple classes in my program, and I'm trying to find a way to use some methods in one of my other classes. Normally I would just do:
Class obj = new Class();
but that creates a new Instance of it and since I'm using HashMaps, that doesn't work because it creates a new map. I want it to use the same HashMap with stuff already saved in it. What is the best way of doing this?
Edit: Heres an example of the code I'm talking about:
Class #1:
public class Foo{
HashMap<String,Integer> hashmap = new HashMap<String,Integer();
hashmap.put("something", 1);
}
Class #2:
public class Foo2{
Foo f = new Foo();
f.get("something");
}
and nothing shows up for f.get because I created a new version of it...could somebody correct this code for me so I can see what you guys are talking about?
You need to share object references
public class Main {
public static class Foo{
Map<String, Integer> map;
public Foo(Map<String, Integer> map) {
this.map = map; // don't create a new object,
// use one that already exists that can be passed as an argument
}
public void put(String key, Integer value) {
map.put(key, value);
}
public Integer get(String key) {
return map.get(key);
}
}
public static void main(String[] args) {
Map<String, Integer> someMap = new HashMap<>();
someMap.put("aKey", 42);
Foo foo = new Foo(someMap); // the Foo object now references the map you just created
System.out.println(foo.get("aKey")); // prints 42
}
}
Here, you create a Map and pass a copy of its reference as an argument to your class' constructor. Your class saves this reference and uses it to access the same object.
When sharing objects, it's important to know what you are doing so that updates aren't lost/overwritten.
This is also another possible way to do. Extend hashmap and make the class as singleton.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
class ExtHashMap<K,V> extends HashMap<Object,Object> {
private static HashMap<?, ?> map;
public static HashMap<?, ?> getInstance() {
if (map == null) {
map = new HashMap<Object,Object>();
}
return map;
}
private ExtHashMap() {
super();
}
}
public class SampleUtil {
/**
* #param args
*/
public static void main(String args[]) throws Exception {
HashMap map = ExtHashMap.getInstance();
map.put("1", "v1");
HashMap map1 = ExtHashMap.getInstance();
map1.put("2", "v2");
System.out.println(map1.values());
}
}