I have a map object testMap declared as HashMap<String, Test>.
Test is a simple class which contains references to an Object and to two String values.
ie,
public class Test {
private String name;
private String id;
private Object val;
public Test(Object val,String name.String id){
this.val =val;
this.id=id;
this.name = name;
}
I want to update the "name" only in the Hash map "testMap." How can I do this?
Test test = testMap.get("key");
if (test != null) {
test.name = "new name";
}
You need to change the visibility of your name property to public or add a setter to it:
public class Test {
private String name;
private String id;
private Object val;
public Test(Object val,String name, String id){
this.val =val;
this.id = id;
this.name = name;
}
public void setName(String name) {
this.name = name;
}
Then, to change your name, you need to
Test test = testMap.get("key");
if (test != null) {
test.setName("new name");
}
If you want to update the Map key also, then you need
Test test = testMap.remove("oldKey");
if (test != null) {
test.setName("newKey");
test.put("newKey", test);
}
Test test = testMap.remove("name");
if(test != null)
test.put("newname",test);
It is not possible with the current implementation of Test you have, since the name is a private field. You can make it public or add getter/setter methods to the Test class (currently the Test class seems to be completely useless unless you haven't missed some code).
After that, you can either replace the desired instance of Test with a new one with necessary fields, or update the name. Code:
public class Test {
public String name;
public String id;
public Object val;
public Test(Object val,String name.String id){
this.val =val;
this.id=id;
this.name = name;
}
}
Map<String, Test> testMap = new HashMap<String, Test();
...
Test test = testMap.get(key);
test.name = newName;
testMap.put(key, test);
// or
Test test2 = testMap.get(key);
testMap.put(key, new Test(test2.val, newName, test2.id));
Related
Using Retrofit here to consume Google Civic API.
The library requires you to create a model of what the API will return as I have done already with Election. Which is basically a copy of the google documentation.
(Retrofit binds the response properties to properties with the same name)
Election.Java :
public class Election {
private long id;
private String name;
private String electionDay;
private String ocdDivisionId;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getElectionDay() {
return electionDay;
}
public void setElectionDay(String electionDay) {
this.electionDay = electionDay;
}
public String getOcdDivisionId() {
return ocdDivisionId;
}
public void setOcdDivisionId(String ocdDivisionId) {
this.ocdDivisionId = ocdDivisionId;
}
}
But Representatives have an inconsistent property name, thus I don't see a way to model this in a way Retrofit will know how to deserialize the API's response.
Representatives object (JSON) :
property name is called (key)
How do I let Retrofit deserialize a model that captures the property named variable after a key of the division?
Assuming you're using a Gson converter, I personally would use a map. I guess the same can be achieved with other converters, but I never used them. Say you have the following object:
public class Division {
#SerializedName("name")
#Expose
private String name;
#SerializedName("alsoKnownAs")
#Expose
private List<String> alsoKnownAs = new ArrayList<>();
#SerializedName("officeIndices")
#Expose
private List<Integer> officeIndices = new ArrayList<>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getAlsoKnownAs() {
return alsoKnownAs;
}
public void setAlsoKnownAs(List<String> alsoKnownAs) {
this.alsoKnownAs = alsoKnownAs;
}
public List<Integer> getOfficeIndices() {
return officeIndices;
}
public void setOfficeIndices(List<Integer> officeIndices) {
this.officeIndices = officeIndices;
}
}
Which represents the object inside the divisions array. You can then have the class:
private class Divisions {
#SerializedName("divisions")
#Expose
private Map<String, Division> divisions = new HashMap<>();
// ...
}
Notice the usage of a map here? Behind the scenes Gson will be able to serialise and deserialise your objects. The class Divisions is the root of the json you gave us in the question.
Hope this helps
I have two packages lets give them the name package 1 and package 2.
Class A and Class B is in package1. Class A contains an ArrayList called PTable. Class B contains a function called query() that filters through PTable,in Class A, based on a certain conditions and returns an ArrayList called result that contains all the elements from PTable that meet that condition.
I now have package2 that contains Class C. Class C imports Class B from package 1; Class C is a subclass of HttpServlet. I create an object of Class B in class C and initializer it.
I then call the function query() and assign it to a variable called results. When I try and get the properties of an element at a certain index, I can't see the properties of the original objects stored in the ArrayList PTable.[This is what appears when I try and access the properties of the objects. My aim is to see the second image ][1]
Nice to ask questions but first spend sometime studying Java. Read a book or online and you will learn about casting very quickly. Also about classes, super classes etc
Your storing the objects in a variable of type Element (your results array list).
Cast the object back to the type it belongs too and then you will see the variables.
Code design note : storing different types of classesin the same array list is legal and possible but bug prone. Try to avoid it. If you change the order of storing variables into the list, you need to change all the access code too. Anyway happy learning.
There are free online Java tutorials study them -> https://www.google.co.in/search?q=java+tutorial+beginner
Sample class, in the main method try to get the object at position 1 and cast it to a Person :
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
super();
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Car {
private String manufacturer;
private String model;
private double price;
private int yearOfMfr;
private Date dateBought;
private String licenceNumber;
public Car() {
super();
}
public Car(String manufacturer, String model, double price, int yearOfMfr, Date dateBought, String licenceNumber) {
super();
this.manufacturer = manufacturer;
this.model = model;
this.price = price;
this.yearOfMfr = yearOfMfr;
this.dateBought = dateBought;
this.licenceNumber = licenceNumber;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getYearOfMfr() {
return yearOfMfr;
}
public void setYearOfMfr(int yearOfMfr) {
this.yearOfMfr = yearOfMfr;
}
public Date getDateBought() {
return dateBought;
}
public void setDateBought(Date dateBought) {
this.dateBought = dateBought;
}
public String getLicenceNumber() {
return licenceNumber;
}
public void setLicenceNumber(String licenceNumber) {
this.licenceNumber = licenceNumber;
}
}
public class DemoApp {
public static void main(String[] args) {
List<Object> results = new ArrayList<>();
DemoApp app = new DemoApp();
app.fillItUp(results);
Car acar = (Car) results.get(0);
acar.setLicenceNumber("Flying Duck");
}
private void fillItUp(List<Object> results) {
Car car = new Car("sel2in", "electric_VTOL", 540923, 2018, new Date(2018, 3, 32), "Skyprog");
results.add(car);
results.add(new Person("tushar", 39));
}
}
I'm new to Android and I'm having a problem using String variables from resources in my code. I tried a couple of solutions found on the internet and Android API Guides, but they didn't work in this specific case, could also be me not using them correctly.
To be more specific, I have a Master/Detail flow activity and I would like to use resource strings as item names for multilanguage purposes, but I have a problem with recovering actual strings.
The error I get is:
Cannot resolve method 'getString()'
Here is my code based on android studio dummy file
public class Categories {
public static List<CatName> ITEMS = new ArrayList<CatName>();
static {
String temp = getString(R.string.cat_n1);
addItem(new CatName("1", temp);
}
private static void addItem(CatName item) {
ITEMS.add(item);
}
public static class CatName {
public String id;
public String name;
public FieldCat(String id, String name) {
this.id = id;
this.name = name;
}
#Override
public String toString() {
return name;
}
}}
You need to specify the resource. Try this,
getResources().getString(R.string.cat_n1);
getString(int resId): Return a localized string from the application's package's default string table.
getResources().getString(int id): Returns the string value associated with a particular resource ID. It will be stripped of any styled text information.
Try using it with a constructor passing the context and calling getstring on that
public class Categories {
public static List<CatName> ITEMS = new ArrayList<CatName>();
public Categories(Context ct)
{
String temp = ct.getString(R.string.abc_action_bar_home_description);
addItem(new CatName("1", temp));
}
private static void addItem(CatName item) {
ITEMS.add(item);
}
public static class CatName {
public String id;
public String name;
public CatName(String id, String name) {
this.id = id;
this.name = name;
}
#Override
public String toString() {
return name;
}
}}
I'm coming to Java from Python and thought that this is basically like Python's self...but this small code confuses me. Functionally, this code:
public class Test {
private String name;
public Test(String givenName)
{
this.name = givenName;
}
public String nameGet()
{
return this.name;
}
public static void main(String[] args)
{
Test example = new Test("Hello Guys");
System.out.println(example.nameGet());
}
}
does the same exact thing as this code:
public class Test {
private String name;
public Test(String givenName)
{
name = givenName;
}
public String nameGet()
{
return name;
}
public static void main(String[] args)
{
Test example = new Test("Hello Guys");
System.out.println(example.nameGet());
}
}
Since this, pardon the pun, seems to be the case, what then is the point of referring to this when working within the class?
public Test(String givenName)
{
this.name = givenName;
}
The this. is not needed in this case or in the get method). It is commonly used when the code is like this instead:
public Test(String name)
{
this.name = name;
}
Which tells the compiler to set the instance variable (this.name) to the local variable (name).
Some people do it to be very clear that they are using an instance variable.
It's often not needed but may be necessary in case of ambiguity.
Say your constructor parameter was called name then there would be no way of determining which variable you're referring to.
Thus you would have to use:
public class Test {
private String name;
public Test(String name) {
this.name = name;
}
}
(On a side note; if you'll ever work with inner classes and you've got name ambiguity you use OuterClass.this:
public class Test {
private String name;
private class InnerTest {
InnerTest(String name) {
Test.this.name = name;
}
}
public Test(String name) {
new InnerTest(name);
}
}
I'm using BlazeDS in Tomcat7 and Flex. I'm trying to use custom classes between the client and server.
In as:
package
{
[Bindable]
[RemoteClass(alias="remoting.Product")]
public class Product
{
public var name:String;
public var id:int;
public var isVisible:Boolean;
}
}
In Java:
package remoting;
public class Product {
public String name;
public int id;
public Boolean isVisible;
public Product(){
name = "Product 0.1";
id = 123;
isVisible = false;
}
public void setName(String _name){
name = _name;
}
public void setId(int _id){
id = _id;
}
public void setVisible(Boolean _isVisible){
isVisible = _isVisible;
}
}
Service part:
public Product echo() {
Product product = new Product();
product.setId(123);
product.setName("My Product");
product.setVisible(true);
return product;
}
I can successfully set the destination of the RemoteObject and call the echo() method. The result event fires up, with the Product object in event.result. However, it does not contain any sensible data. The variables from AS class just get initialized with null, 0 and true values. I'm wondering what's the problem. I tried returning a String with parameters from Product and it works fine, so they get set fine. The problem is in mapping.
I could go another way and implement Externalizable but I don't understand this part from the example:
name = (String)in.readObject();
properties = (Map)in.readObject();
price = in.readFloat();
What if there is a number of strings?
Cheers.
In java class: use private fields and implement getters.
package remoting;
public class Product {
private String name;
private int id;
private Boolean isVisible;
public Product() {
name = "Product 0.1";
id = 123;
isVisible = false;
}
public void setName(String _name){
name = _name;
}
public String getName(){
return name;
}
public void setId(int _id){
id = _id;
}
public int getId(){
return id;
}
public void setIsVisible(Boolean _isVisible){
isVisible = _isVisible;
}
public Boolean getIsVisible() {
return isVisible;
}
}
You could also switch from BlazeDS to GraniteDS: the latter has a powerful transparent externalization mechanism as well as code generation tools that can really save your time (see documentation here).