Static Objects are not getting stored in HashMap.! - java

I am trying to create a Map with key as a String and Value as a static class. But when I am printing the data, it only stores the last key-value pair. Can someone help me with this.
import java.util.HashMap;
import java.util.Map;
public class MapImplementation {
public static class Asset {
public static String assetName;
public static String assetType;
private void setAssetName(String name) {
Asset.assetName = name;
}
private void setAssetType(String type) {
Asset.assetType = type;
}
private String getAssetName() {
return assetName;
}
private String getAssetType() {
return assetType;
}
}
public static void main(String[] args) {
Map<String, Asset> map = new HashMap<>();
Asset asset1 = new Asset();
asset1.setAssetName("Vodafone");
asset1.setAssetType("STOCK");
map.put("Vodafone", asset1);
Asset asset2 = new Asset();
asset2.setAssetName("Google");
asset2.setAssetType("STOCK");
map.put("Google", asset2);
Asset asset3 = new Asset();
asset3.setAssetName("IBM");
asset3.setAssetType("BOND");
map.put("IBM", asset3);
for (String str : map.keySet()) {
Asset ast = map.get(str);
System.out.println(ast.getAssetName()+" "+ast.getAssetType());
}
}
}
The output I am getting is:
IBM BOND
IBM BOND
IBM BOND

Change:
public static String assetName;
public static String assetType;
to:
public String assetName;
public String assetType;
static fields are class level, not instance level - they are shared across all instances. Even though you are calling setters of different objects, the exact same 2 fields are being updated in those methods.

Related

Java static List

I want to pass a static list through an interface.
So that I can execute the following code.
updateSingleItem(new InformationListModule(getNameByUUID(uid), value));
I am looking for the cleanest way to create a static list where I can output the name based on an ID. I want to pass this list to different classes.
How can I create a static list with which I can execute the command "getNameByUUID(uid)".
Maybe someone can tell me what is the cleanest solution and give a small example.
would be glad.
Vielen Lieben dank.
I have now implemented it this way.
public abstract class BluetoothUUIDs {
/* UUID SERVICES */
public static final HashMap<String, String> BLE_SERVICE_UUID_NAME;
public static final HashMap <String, String> BLE_SERVICE_UUID_TYPE;
/* UUID ATTRIBUTES */
...
{
/* UUID SERVICES TO NAME */
BLE_SERVICE_UUID_NAME = new HashMap<>();
.....
BLE_SERVICE_UUID_TYPE.put("1800","org.bluetooth.service.generic_access");
...
I don't know if it's the best, but it's a way.
You could consider using an EnumMap.
import java.util.EnumMap;
public enum UUIDs {
UUID_1("1800", "org.bluetooth.service.generic_access"),
// additional UUID‘s..
private final String uuid;
private final String name;
UUIDs(String uuid, String name) {
this.uuid = uuid;
this.name = name;
}
public String getUuid() {
return uuid;
}
public String getName() {
return name;
}
private static final EnumMap<UUIDs, String> uuidToName = new EnumMap<>(UUIDs.class);
private static final EnumMap<UUIDs, String> uuidToType = new EnumMap<>(UUIDs.class);
static {
for (UUIDs uuid : UUIDs.values()) {
uuidToName.put(uuid, uuid.getName());
uuidToType.put(uuid, uuid.getUuid());
}
}
public static String getNameByUuid(String uuid) {
for (UUIDs u : UUIDs.values()) {
if (u.getUuid().equals(uuid)) {
return u.getName();
}
}
return null;
}
public static String getUuidByName(String name) {
for (UUIDs u : UUIDs.values()) {
if (u.getName().equals(name)) {
return u.getUuid();
}
}
return null;
}
}
You can access the EnumMap in other classes by calling the methods getNameByUuid and getUuidByName.
String name = UUIDs.getNameByUuid("1800");
String uuid = UUIDs.getUuidByName("org.bluetooth.service.generic_access");
This is a suggestion you could try/use.

Java Serializable and lambda expressions

I need to save an object on file, then retrieve it later. The object itself implements the interface Serializable, but one of its fields contains lambda expressions. Apparently this counts as a field that does not implements the Serializable interface and I get a java.io.NotSerializableException.
I do not want to drastically change my code, but I do not know what to do in such a situation. Someone has a suggestion?
Here is a sample code that replicates this problem:
public class SerObject implements Serializable {
/**
*
*/
private static final long serialVersionUID = -2691834780794406081L;
public SerField field;
public SerObject(SerField field) {
this.field = field;
}
public String stringRepresentation() {
return this.field.name() + "\t" + field.lambda.apply(field);
}
static final String pathname = "D:\\JavaData\\file.obj";
public static void main(String[] args) {
SerObject obj = new SerObject(new SerField("Field", (field) -> "Class is " + field.getClass().getName() ));
SerializableUtilities.saveObject(new File(pathname), obj);
SerObject loadedObj = SerializableUtilities.loadObject(new File(pathname));
System.out.println(loadedObj.stringRepresentation());
}
}
public class SerField implements Serializable {
/**
*
*/
private static final long serialVersionUID = -5058433150929459799L;
protected String name;
protected Function<SerField, String> lambda;
public SerField(String name, Function<SerField, String> lambda) {
this.name = name;
this.lambda = lambda;
}
public abstract String name() {
return this.name;
}
}

Sequence Diagram into Java Codes : How to?

Goodday everyone. I'm actually having some trouble with these Sequence Diagrams. It says that " All animals live in their own cage depending on the race. " I really need a help with this simple diagram because i really dont know how to write it in my Java program. im sure its simple for most of yall. So please help me! here is the Diagram :
Zookeeper class / Mainclass :
package General;
import Zoo.Cage;
public class ZooKeeper {
public static void main(String[] args){
Cage cage1 = new Cage();
}
}
Cage class :
public class Cage {
private String type;
private ArrayList<Animal> cagedAnimals;
public Cage(String type){
this.type = type;
}
public Cage() {
}
public Animal selectAnimal(){
return null;
}
public void getCageType(){
}
public boolean addAnimal(Animal anAnimal){
return true;
}
public ArrayList<Animal> getCagedAnimals(){
ArrayList<Animal> i = new ArrayList<>();
return i;
}
public void addReptileEggs(ArrayList<Egg> reptileEggs){
}
}
Zoo class :
package Zoo;
import General.Animal;
import General.Egg;
import java.util.ArrayList;
import java.util.TreeSet`;
public class Zoo {
private final String name;
private TreeSet<Cage> cages;
/* private ArrayList<Cage> cages;*/
private String Zoo;
private static Zoo instance = new Zoo();
public Zoo() {
this.name = "AnimalK";
}
public static Zoo getInstance() {
if (instance == null) {
instance = new Zoo();
}
return instance;
}
}
You can see that everything happens in the constructor Cage():
public Cage() {
Zoo z = Zoo.getInstance("ICO41A");
boolean b = z.addCage(this);
}
Note that z could be a field if we need to use it later.
Class Zoo now: we've seen that getInstance has a String argument; I assume it's the name of the Zoo, and, instead of a single static instance, we can keep a static Map<String,Zoo>:
public class Zoo {
private static Map<String,Zoo> instances = new HashMap<>();
public static Zoo getInstance(String name) {
Zoo instance = instances.get(name);
if (instance == null) {
instance = new Zoo(name);
instances.put(name, instance);
}
return instance;
}
The name is passed to the constructor, and the Set cages is initialized (with an empty HashSet). I've used a HashSet instead of a TreeSet because Cage is not a Comparable:
private final String name;
private final Set<Cage> cages = new HashSet<>();
private Zoo(String name) {
this.name = name;
}
And finally, method addCage adds a Cage to the set:
public boolean addCage(Cage cage) {
return cages.add(cage);
}

JAVA - how to use Enum as public static final String in different classes?

I want to store constants in one class, and have access to it from different classes.
This is how I created a class for constants, "Keys"
public class Keys {
public static class SQLite {
public static final int DB_VERSION = 8;
public static final String DB_NAME = "my_db.sqlite";
public static final String TABLE_NAME = "table_name";
public enum Column {
NAME("name"),
PHONE("phone"),
ADDRESS("address");
private String value;
Column(String value) {
this.value = value;
}
public String toString() {
return value;
}
}
}
public static class Constants {
public static final String CONST1 = "const1";
public static final String CONST2 = "const2";
public enum Random {
ONE("one"),
TWO("two"),
THREE("three");
private String value;
Random(String value) {
this.value = value;
}
public String toString() {
return value;
}
}
}
}
Now, inside a class called "MyActivity",
I know I can use enums like this:
String name = Keys.SQLite.Column.NAME.toString();
But is there a way to shorten the prefix?
so that I can access it in a simpler way:
Column.Name.toString();
instead of:
Keys.SQLite.Column.Name.toString();
As Azodious already stated, you can import it via
import Keys.SQLite.Column;
If that does not suffice your needs, you may also use a static import, like:
import static Keys.SQLite.Column.NAME;
This way you can now use
String name = NAME.toString();
You can import the enum in MyActivity class:
import Keys.SQLite.Column;
and just use
String name = Column.NAME.toString();
Directly import the enum in your class:
import Keys.SQLite.Column;
and then type Enum name and enum which you want to get :
Column.NAME;

Get java object by id

What I am trying to achieve is to update an object's value with only his ID known:
How can I get the object with a corresponding ID?
So that I can update a property?
class forest
public class forest {
public forestName;
public forest(String forestName){
this.forestName=forestName;
}
updateTreeName(int id, String Name){
// Here I need to update the name of the tree with that specific ID
}
public static void main(String[] args) {
forest greenforest = new forest();
// create some tree's in the greenforest.
greenforest.updateTreeName(4, "red leafe");
}
}
class tree
public class tree {
public String treeName;
public int id;
public tree(int id, String treeName){
this.treeName=treeName;
this.id=id;
}
}
Use HashMap to keep objects. Then use the get method to get the object with the given id.
public class Forest {
public String forestName;
HashMap<Integer, Tree> trees = new HashMap<>();
public Forest(String forestName){
this.forestName=forestName;
//initialize trees
trees.put(4, new Tree(4, "redleaef"));
}
public void updateTreeName(int id, String Name){
trees.get(id).treeName = Name;
}
public static void main(String[] args) {
Forest greenforest = new Forest("name");
// create some tree's in the greenforest.
greenforest.updateTreeName(4, "red leafe");
}
}

Categories