I need to update my Country class so that it can store a list of languages, I also need a field for the list, a getter, and a method that allows me to add a language to the collection. I very green when it comes to programing. This is what I have so far.
public class Country {
private int id;
private String name;
private long population;
private double medianAge;
private List<String> languages;
List<String> list = new ArrayList<>();
/**
* Create a Country object with the given properties
*/
public Country(int id, String name, long population, double medianAge) {
this.id = id;
this.name = name;
this.population = population;
this.medianAge = medianAge;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public long getPopulation() {
return population;
}
public double getMedianAge() {
return medianAge;
}
}
You can remove the member list - cannot see a reason for you to have it.
You constructor can be:
public Country(int id, String name, long population, double medianAge) {
this.id = id;
this.name = name;
this.population = population;
this.medianAge = medianAge;
this.languages = new ArrayList<>();
}
Then you can have a method to add a language to the list:
public void addLanguage (String language) {
languages.add(language);
}
Finally a method to return the list of languages as given below:
public List<String> getLanguages() {
return languages;
}
More information on how ArrayList works
You need a getter method to access languages like below
getLanguages(){
return this.languages;
}
And a method which ads one language to existing list.
addLanguageToList(String language){
this.getLanguages().add(language);
}
Do you mean you want to add an initializer for languages? You can use the list.add() method.
public class Country{
private int id;
private String name;
private long population;
private double medianAge;
private ArrayList<String> languages = new ArrayList<String>();
public Country(int id, String name, long population, double medianAge String language) {
this.id = id;
this.name = name;
this.population = population;
this.medianAge = medianAge;
this.languages.add(laguage);
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public long getPopulation() {
return population;
}
public double getMedianAge() {
return medianAge;
}
}
Its very simple, Create a getter and two add method, one for adding one language and another add method for adding list of language to existing language list.
import java.util.ArrayList;
import java.util.List;
public class Country {
private int id;
private String name;
private long population;
private double medianAge;
private List<String> languages;
List<String> list = new ArrayList<>();
/**
* Create a Country object with the given properties
*/
public Country(int id, String name, long population, double medianAge) {
this.id = id;
this.name = name;
this.population = population;
this.medianAge = medianAge;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public long getPopulation() {
return population;
}
public double getMedianAge() {
return medianAge;
}
public List<String> getLanguages() {
return languages;
}
public void addLanguage(String language) {
this.languages.add(language);
}
public void addLanguages(List<String> languages) {
this.languages.addAll(languages);
}
}
Related
I'm currently trying to create a class in java, to this specification:
I'm not sure how to create "ratings" since I'm seeing its using some
map function using the input of a string and an integer.
Here's my code so far:
public class Movie {
String ID;
String Name;
String Description;
String Genre[];
String Directors[];
String Actors[];
String Language;
String CountryOfOrigin;
}
Please create different objects for genre, director, actor and rating. It will be a best practice when you try to add more information to each entity.
Use access modifier "private" to each attribute and implement get,set methods as required.
Use ArrayLists instead of arrays to avoid resizing efforts when required.
import java.util.ArrayList;
import java.util.List;
public class Genre {
private int id;
private String name;
public Genre(int id, String name) {
this.id = id;
this.name = name;
}
}
public class Director {
private int id;
private String name;
public Director(int id, String name) {
this.id = id;
this.name = name;
}
}
public class Actor {
private int id;
private String name;
public Actor(int id, String name) {
this.id = id;
this.name = name;
}
}
public class Rating {
private int value;
private String name;
public Actor(int value, String name) {
this.value = value;
this.name = name;
}
}
public class Movie {
private int id;
private String name;
private String description;
private List<Genre> generes;
private List<Director> directors;
private List<Actor> actors;
private String language;
private String countryOfOrigin;
pulic Movie(int id, String name, String description, String language, String countryOfOrigin){
this.id = id;
// set other variables
this.actors = new ArrayList<Actor>();
// create other lists
}
public void addGenere(Genre genere){
this.generes.add(genere);
}
// implement other add methods to lists
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I want to create bean in java corresponding to below json
{
"name": "",
"id": "",
"dept": {
"deptId": "",
"deptName": "",
"course": {
"courseId": "",
}
}
}
My idea is to create parent class and keep dept and course as inner private classes and then have getters setters to get or set data and form parent bean. But I am getting error "Change visibility to the public"
How can I access private fields of inner private class to get and set data?
try this way its will work
public class firstClass{
private String name;
private String id;
Department dept;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Department getDept() {
return dept;
}
public void setDept(Department dept) {
this.dept = dept;
}
}
class Department{
private int departId;
private String deptName;
Course course;
public int getDepartId() {
return departId;
}
public void setDepartId(int departId) {
this.departId = departId;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
}
class Course{
private int courseId;
public int getCourseId() {
return courseId;
}
public void setCourseId(int courseId) {
this.courseId = courseId;
}
}
You can't access private fields. Why don't you create a getter and setter for the inner class private fields?
And, maybe you should consider using gson library.
You at least have to make say nested public interfaces, say Dept and Course, with your private (static) nested private classes DeptImpl and SourceImpl.
public class X {
public interface Dept { ... }
private static class DeptImpl extends Dept { ... }
public Dept getDept() { ... }
public Dept createDept(...) {
DeptImpl dept = new DeptImpl(...); ...
return dept;
}
Maybe you need to provide a factory method createDept.
In some cases the implementing class can be anonymous new Dept() { ... }.
You can use Builder Design pattern with immutable Objects:
public class Class {
private final String name;
private final int id;
private final Department dept;
private Class(ClassBuilder classBuilder){
this.name = classBuilder.getName();
this.id = classBuilder.getId();
this.dept = classBuilder.getDept();
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public Department getDept() {
return dept;
}
private static class Department{
private final int deptId;
private final String deptName;
private final Course course;
private Department(DepartmentBuilder departmentBuilder){
this.deptId = departmentBuilder.getDeptId();
this.deptName = departmentBuilder.getDeptName();
this.course = departmentBuilder.getCourse();
}
public int getDeptId() {
return deptId;
}
public String getDeptName() {
return deptName;
}
public Course getCourse() {
return course;
}
private static class Course{
private final int courseId;
private Course(CourseBuilder courseBuilder){
this.courseId = courseBuilder.getCourseId();
}
public int getCourseId() {
return courseId;
}
}
}
public static class ClassBuilder{
private final String name;
private final int id;
private final Department dept;
public ClassBuilder(String name, int id, Department dept){
this.name = name;
this.id = id;
this.dept = dept;
}
public Department getDept() {
return dept;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public Class build(){
return new Class(this);
}
}
public static class DepartmentBuilder {
private final int deptId;
private final String deptName;
private final Department.Course course;
public DepartmentBuilder(int deptId, String deptName, Department.Course course ){
this.deptId = deptId;
this.deptName = deptName;
this.course = course;
}
public int getDeptId() {
return deptId;
}
public String getDeptName() {
return deptName;
}
public Department.Course getCourse() {
return course;
}
public Department build(){
return new Department(this);
}
}
public static class CourseBuilder{
private final int courseId ;
public CourseBuilder(int courseId){
this.courseId = courseId;
}
public int getCourseId() {
return courseId;
}
public Department.Course build(){
return new Department.Course(this);
}
}
}
public class Sample {
public static void main(String ... strings){
Class clazz = new Class.ClassBuilder("ClassName", 1, new Class.DepartmentBuilder(1, "departmentName", new Class.CourseBuilder(2).build()).build()).build();
System.out.println(clazz.getDept());
}
}
There is a Product class. A list of objects of product class is formed and that list is encapsulated within an object of Order class. both the classes are given below.
Product.java
package com.example.gandhjee.pantry_order;
import java.io.Serializable;
public class Product implements Serializable{
private int id;
private String name;
private int amount;
private int final_id;
private int price;
private int price_per_plate;
//private String description;
private static final long serialVersionUID = -5435670920302756945L;
//Constructor
public Product(int final_id,int id, String name, int amount , int price ,int price_per_plate) {
this.id = id;
this.name = name;
this.amount = amount;
this.setName(name);
this.setAmount(amount);
this.setFinal_id(final_id);
this.price_per_plate = price_per_plate;
this.final_id = final_id;
this.price = price;
}
public int getPrice_per_plate(){
return price_per_plate;
}
public int getPrice(){
return price;
}
public void setPrice(int price){
this.price = price;
}
public void setFinal_id(int final_id){
this.final_id=final_id;
}
public int getFinal_id(){
return final_id;
}
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public int getAmount(){
return amount;
}
public void setAmount(int amount){
this.amount = amount;
}
}
Order.java
package com.example.gandhjee.pantry_order;
import java.io.Serializable;
import java.util.List;
public class Order implements Serializable{
private int order_id;
private List<Product> mProductList;
private String emp_name;
private int area_id;
private int emp_id;
private int conf_room_id;
private int type_id;
//private String description;
private static final long serialVersionUID = -5435670920302756945L;
public Order(List<Product> mProductList, int order_id,int emp_id, String emp_name, int type_id , int area_id ,int conf_room_id ){
this.mProductList = mProductList;
this.order_id = order_id;
this.emp_name = emp_name;
this.emp_id = emp_id;
this.setType_id(type_id);
this.setconf_room_id(conf_room_id);
this.setArea_id(area_id);
}
public void setmProductList(List<Product> mProductList){
this.mProductList = mProductList;
}
public Product getmProductList(){
return (Product) mProductList;
}
public int getConf_room_id(){
return conf_room_id;
}
public void setconf_room_id(int conf_room_id){
this.conf_room_id = conf_room_id;
}
public int getArea_id(){
return area_id;
}
public void setArea_id(int area_id){
this.area_id = area_id;
}
public void setType_id(int type_id){
this.type_id=type_id;
}
public int getType_id(){
return type_id;
}
public int getOrder_id(){
return order_id;
}
public String getEmp_name(){
return emp_name;
}
public void setEmp_name(String emp_name){
this.emp_name = emp_name;
}
public int getEmp_id(){
return emp_id;
}
public void setEmp_id(int emp_id){
this.emp_id = emp_id;
}
}
Now I want to send an Object of Order class from my mobile application to a web service in PHP using Volley library. I searched a lot on the internet but there is no example given for sending an Object within an object from a mobile application to a web service. Any help would be appreciated . Thank you in advance!
Create a JSONObject and send that to the server.
You can either do it manually usally net.json or (that's what I suggest you) use Gson.
Here you can find a tutorial to implement it for your use:
https://guides.codepath.com/android/Leveraging-the-Gson-Library
in C# you can create a instance of a class and set the values of variables at the same time:
public class Object
{
public virtual long Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int Version { get; set; }
public long ParentId { get; set; }
}
public class Start
{
Object object= new Object()
{
Id = 1,
Name = name,
ParentId = parentId,
Description = null,
Version= 2
};
}
Is this possible in Java aswell and how?
The standard way for setting values when creating an instance is to just have a constructor:
class ExampleObject {
long id;
String name;
String description;
int version;
long parentId;
public ExampleObject(final long id, final String name, final String description, final int version, final long parentId) {
this.id = id;
this.name = name;
this.description = description;
this.version = version;
this.parentId = parentId;
}
}
And then call it like:
ExampleObject exampleObject = new ExampleObject(1, name, null, 2, parentId);
It is possible to use a similar syntax to what you have shown, but it has quite a few downsides which you should research about before using it (and you also cannot use variables with this):
ExampleObject exampleObject = new ExampleObject() {{
id = 1;
name = "";
parentId = 2;
description = null;
version = 2;
}};
class ExampleObject {
long id;
String name;
String description;
int version;
long parentId;
}
What this does is creates an anonymous class with a static initialiser block. A static initialiser block looks like:
class ExampleObject {
long id;
String name;
String description;
int version;
long parentId;
{
id = 1;
name = "";
parentId = 2;
description = null;
version = 2;
}
}
You can create a constructor that accepts values for all the fields. This way, you can create a new instance of that object and set the values you want at the same time:
public class MyClass {
public long id;
public String name;
public String description;
public int version;
public long parentId;
/** Constructor **/
public MyClass(long id, String name, String description, int version, long parentId) {
this.id = id;
this.name = name;
this.description = description;
this.version = version;
this.parentId = parentId;
}
}
public static void main(String args[]) {
MyClass myClass = new MyClass(1, "name", "description", 1, 1);
}
By the way, it's not recommended (although you can) to name a class Object in Java, since Java also has a class with that very same name, and all Java classes extend from it (can lead to confussion).
public class Object
{
public long id;
public String name;
public String description;
public int version;
public long parentId;
public Object(long Id,string Name,string Description,int Version,long Parent_Id)
{
this.Id =Id ;
this.Name =Name ;
this.Description =Description ;
this.Version =Version ;
}
I am developing and spring application and for object mapping I am using ModelMapper library.
I am able to map basic class mapping but when I am trying to map 2 collection elements, source is set of enumeration with additional property like name and description and destination is pojo having id, name and description.
I have tried typemap and converters in mapping profile but I am getting exception of mapper.
And the source class is from other application(whose dependency have been added in pom.xml). I also don't want source type as an argument in setter of destination.
Ex.
SOURCE:
public class VType{
private int id;
private String name;
private String description;
}
public class VDTO{
private Set<VType> vTypes;
public Set<VType> getVTypes(){
return this.vTypes;
}
public void setVType() { //here I don't want to pass source type as an argument
//code stuff that I don't know what to do here
}
}
SOURCE ENUM:
public enum SourceVType{
V1(1, "Name1", "Desc1");
V2(2, "Name2", "Desc2");
private Integer id;
private String name;
private String description;
SourceVType(Integer id, String name, String description) {
this.id = id;
this.name = name;
this.description = description;
}
//getter-setter
}
Have you tried converter feature of modelmapper. You can use typemap converter to achieve this requirement.
#RunWith(JUnit4.class)
public class TempTest {
#Test
public void TestThis(){
final ModelMapper mapper = new ModelMapper();
mapper.addMappings(new PropertyMap<SrcClass, DestClass>() {
#Override
protected void configure() {
this.map().setId(this.source.getId());
this.map().setName(this.source.getName());
mapper.createTypeMap(TypeEnum.class, TypeClass.class).setConverter(
new Converter<TypeEnum, TypeClass>() {
#Override
public TypeClass convert(MappingContext<TypeEnum, TypeClass> mappingContext) {
if (mappingContext.getSource() == null) {
return null;
}
TypeEnum typeEnum = mappingContext.getSource();
TypeClass typeClass = new TypeClass();
typeClass.setId(typeEnum.getId());
typeClass.setName(typeEnum.getName());
return typeClass;
}
});
}
});
SrcClass srcObj = new SrcClass();
srcObj.setId(1);
srcObj.setName("name");
srcObj.setTypes(new HashSet<>(Arrays.asList(TypeEnum.TYPE1, TypeEnum.TYPE2)));
DestClass dstObj = mapper.map(srcObj, DestClass.class);
Assert.assertEquals(srcObj.getId(), dstObj.getId());
Assert.assertEquals(srcObj.getName(), dstObj.getName());
Assert.assertEquals(srcObj.getTypes().size(), dstObj.getTypes().size());
for(TypeClass c : dstObj.getTypes()) {
TypeEnum e = TypeEnum.getById(c.getId());
Assert.assertNotNull(e);
Assert.assertTrue(srcObj.getTypes().contains(e));
}
}
public static <Source, Result> Set<Result> convertAll(Set<Source> source, Function<Source, Result> projection)
{
Set<Result> results = new HashSet<>();
if(source == null) return results;
for (Source element : source)
{
results.add(projection.apply(element));
}
return results;
}
public static class SrcClass{
private Integer id;
private String name;
private Set<TypeEnum> types;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<TypeEnum> getTypes() {
return types;
}
public void setTypes(Set<TypeEnum> types) {
this.types = types;
}
}
public static class DestClass{
private Integer id;
private String name;
private Set<TypeClass> types;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<TypeClass> getTypes() {
return types;
}
public void setTypes(Set<TypeClass> types) {
this.types = types;
}
}
public static enum TypeEnum{
TYPE1(1, "Type 1")
, TYPE2(2, "Type 2")
, TYPE3(3, "Type 3")
, TYPE4(4, "Type 4");
private Integer id;
private String name;
TypeEnum(Integer id, String name) {
this.id = id;
this.name = name;
}
private static final Map<Integer, TypeEnum> byId = new HashMap<>();
private static final Map<String, TypeEnum> byName = new HashMap<>();
static {
for (TypeEnum e : TypeEnum.values()) {
if (byId.put(e.getId(), e) != null) {
throw new IllegalArgumentException("duplicate id: " + e.getId());
}
if (byName.put(e.getName(), e) != null) {
throw new IllegalArgumentException("duplicate name: " + e.getName());
}
}
}
public Integer getId() {
return this.id;
}
public String getName() { return this.name; }
public static TypeEnum getById(Integer id) {
return byId.get(id);
}
public static TypeEnum getByName(String name) {
return byName.get(name);
}
}
public static class TypeClass{
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}