Java remove User defined object from Tree Set - java

I have created a class of Patient object containing patient name and gender and I want to remove it base on Patient name. What is the correct way to do it?
This is my Patient object:
class Patient {
private String name;
private int gender;
public Patient(String name, int gender){
this.name = name;
this.gender = gender;
}
public String getName(){
return this.name;
}
public int getGender(){
return this.gender;
}
public void setName(String name){
this.name = name;
}
public void setGender(int gender){
this.gender = gender;
}
}
This is my Treeset declaration: private TreeSet<Patient> ts = new TreeSet<Patient>(new nameComp());
This is my remove method (I don't know how to start)
void RemovePatient(String patientName) {
}

Just iterating and removing while doing so, will result in a Concurrent Modification Exception. You could temp save the item to remove and remove it later:
For example:
void removePatient(String patientName) {
Person deleteThat;
for (Patient p : ts){
if(p.getName().equals(patientName){
deleteThat = p;
}
}
if(deleteThat != null){
ts.remove(deleteThat);
}
}

Related

How to extract field value from another field that is of type Object

I'm new to java reflexion and I'm trying to integrate SQLite with java.
I have 2 objects Person and Department. There is relation OneToMany between them.
As I'm working on save functionality (SQLite) I want to extract field names and its values so I can build full query. I have no problem with extracting names and values of fields that are of primitive type (String, int etc.). I have problem with type of Object (in this case it is Department field in Person object).
I'm able to print object but unable to access its fields (namely pk).
Could you help me please?
METHOD FOR EXTRACTING FIELDS
// method for extracting fields
private StringBuilder getFieldsWithValues(Object entity) throws IllegalAccessException, NoSuchFieldException {
StringBuilder query = new StringBuilder();
for (Field field : entity.getClass().getDeclaredFields()) {
System.out.print((field.getName() + " - "));
field.setAccessible(true);
// TODO: eliminate if statement from for cycle
if (field.isAnnotationPresent(ManyToOne.class)) {
// HERE I want to extract the pk value from Department object
System.out.println(field.get(entity));
} else {
System.out.println(field.get(entity));
}
}
return query;
}
DEPARTMENT OBJECT
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Department {
#Id
private long pk;
private String name;
private String code;
public Department() {
}
public Department(String name, String code) {
this.name = name;
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String toString() {
return String.format("Department %d: %s (%s)", pk, name, code);
}
}
PERSON OBJECT
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
#Entity
public class Person {
#Id
private long id;
private String surname;
private String name;
private int age;
#ManyToOne
private Department department;
public Person(String surname, String name, int age) {
this.surname = surname;
this.name = name;
this.age = age;
}
public Person() {
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public long getId() {
return id;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
#Override
public String toString() {
return String.format("Person %d: %s %s (%d)", id, surname, name, age);
}
}

Is there a way to add an instance variable to an existing class through the backend?

I am trying to build a table that can be modified and stored in a sql database. I am using mybatis to access my sql database. I want to be able to take a String from the user and add a column to the existing table that I have. In order to add a column to the sql table, I need to modify the class that fetches the data, and this class needs to have an instance variable added and the constructor modified to be able to fetch the data.
For example, This is one of my Mapper classes that relies on the Employee class to fetch data from the database.
#Mapper
public interface EmployeeMapper {
#Select("SELECT * FROM employee")
List<Employee> findEmployees();
#Select("SELECT * FROM employee WHERE list_UserName = #{list};")
List<Employee> employeeForUser(String list);
#Insert("INSERT INTO employee(name, email, position, list_UserName) values (#{name}, #{email}, #{position}, #{list_UserName});")
void addEmployee(Employee employee);
#Delete("DELETE FROM employee WHERE id = #{id}")
void deleteEmployee(int id);
}
Employee Class:
public class Employee {
private int id;
private String name;
private String email;
private String position;
private String list_UserName;
public Employee(int id, String name, String email, String position, String list_UserName) {
this.id = id;
this.name =name;
this.email = email;
this.position = position;
this.list_UserName = list_UserName;
}
public String getList_UserName() {
return list_UserName;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getPosition() {
return position;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setEmail(String email) {
this.email = email;
}
public void setPosition(String position) {
this.position = position;
}
}
Here is my controller for this case:
#RequestMapping(value="/list", method = RequestMethod.POST)
public String newEmployee(Model model, #RequestParam String EmployeeName, #RequestParam String EmployeeEmail, #RequestParam String EmployeePosition, HttpSession session) {
if(!sessionFound(session.getId())){
return "redirect:/login";
}
if(isNewEmployee(returnUser(session.getId()).getUser_name(), EmployeeName, EmployeeEmail, EmployeePosition)) {
Employee temp = new Employee(0, EmployeeName, EmployeeEmail, EmployeePosition, returnUser(session.getId()).getUser_name());
employeeMapper.addEmployee(temp);
return "redirect:/list";
}
model.addAttribute("employeeMessage", "Employee Already Exists");
return "redirect:/list";
}
In this case, I want to be able to alter the table(which I know how to do) and add an instance variable to the Employee class based on the User's request(which I do not know how to do). How do I do that?

Deserialization fails when there is no default constructor

I 'm trying to use Fastjson library for JSON serialization.
When I try to deserialize , it fails showing no default constructor error.
Note: My class here is a toy example. I realty, it contains so many references to other classes which are in other maven projects and its practically not possible to modify every class.
Here is the code.
Student s = new Student("vineel", "20");
String hell = JSON.toJSONString(s);
Student model2 = JSON.parseObject(hell, Student.class);
System.out.println(model2);
public class Student {
private String name;
private String age;
Student(String name,String age){
this.name = name;
this.age = age;
}
#override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
Here is the error:
Exception in thread "main" com.alibaba.fastjson.JSONException: default constructor not found. class com.alibaba.fastjson.Student
at com.alibaba.fastjson.util.JavaBeanInfo.build(JavaBeanInfo.java:467)
at com.alibaba.fastjson.util.JavaBeanInfo.build(JavaBeanInfo.java:213)
at com.alibaba.fastjson.parser.ParserConfig.createJavaBeanDeserializer(ParserConfig.java:656)
at com.alibaba.fastjson.parser.ParserConfig.getDeserializer(ParserConfig.java:573)
at com.alibaba.fastjson.parser.ParserConfig.getDeserializer(ParserConfig.java:386)
at com.alibaba.fastjson.parser.DefaultJSONParser.parseObject(DefaultJSONParser.java:658)
at com.alibaba.fastjson.JSON.parseObject(JSON.java:365)
at com.alibaba.fastjson.JSON.parseObject(JSON.java:269)
at com.alibaba.fastjson.JSON.parseObject(JSON.java:488)
at com.alibaba.fastjson.JSON.main(JSON.java:1068)
Change constructor to.
#JsonCreator
public Student(#JsonProperty("name") String name, #JsonProperty("age") String age){
this.name = name;
this.age = age;
}
So create a TO class.
Student model2 = JSON.parseObject(hell, StudentTO.class).asStudent();
System.out.println(model2);
public class StudentTO {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public Student asStudent() {
return new Student(name, age);
}
}

Good Practice to extend models?

I'm using the following model in a listview:
public class ListItem {
private int _Id;
private String Name;
public ListItem() {
this._Id = 0;
this.Name = "";
}
public ListItem(int Id, String Name) {
this._Id = Id;
this.Name = Name;
}
public int getId() {
return this._Id;
}
public void setId(int c) {
this._Id = c;
}
public String getName() {
return this.Name;
}
public void setName(String c) {
this.Name = c;
}
}
I have some extra data that will be displaying once they click on the item they want to view. Since I'm pulling this info from a database and I'm not limiting the number of items they put in the database, I was wondering if I could extend my model in another model. Something like (you can correct me if this is the wrong way to write an extend model, if extending models is not a big deal):
public class ItemDetails extends ListItem {
private String itemType, Manufacturer, Qty, Notes;
public ItemDetails () {
this._Id = 0;
this.Name = "";
this.itemType = "";
this.Manufacturer = "";
this.Qty = "";
this.Notes = "";
}
public Ammo(int _Id, String name, String itemType,
String manufacturer, String qty, String notes) {
this._Id = _Id;
this.Name = name;
this.itemType = itemType;
this.Manufacturer = manufacturer;
this.Qty = qty;
this.Notes = notes;
}
// Get Variables //
public int get_Id() {
return this._Id;
}
public String getName() {
return this.Name;
}
public String getItemType() {
return itemType;
}
public String getManufacturer() {
return Manufacturer;
}
public String getQty() {
return Qty;
}
public String getNotes() {
return Notes;
}
// Set Variables //
public void set_Id(int c) {
this._Id(c);
}
public void setName(int c) {
this.Name = c;
}
public void setItemType(String c) {
itemType = c;
}
public void setManufacturer(String c) {
Manufacturer = c;
}
public void setQty(String c) {
Qty = c;
}
public void setNotes(String c) {
Notes = c;
}
}
Would this be a bad idea? Would I be better off just having to different models or one model and only returning the data I need from the List then getting the rest of the data later? I'm trying to write clean code with this, and have as little duplicate code as possible. I am also wanting my code to be efficient and perform well , but I'm not sure if this might be a good idea.
It looks like you're not using most of the code (variables and methods) from the class you are extending from. If you don't explicitly need to get an object of ListItem when you create an object of ItemDetails (like ListItem item = new ItemDetails();) you have actually no reason to extend that class. In that case your code is definitely cleaner, if you make it not to extend.
If you want to write clean code you should understand that the constructor calls the ListItem constructor and already initializes fields "_Id" and "Name" and overriding methods with no need to change them is not recommended.

ArrayList Java Addition

Please help me to why am getting strange output for this Below Code.....
why am getting null for the getName().
Output :
List Check :null:1
public class ListTest
{
public static void main(String args[])
{
List<Movie> lst = new java.util.ArrayList<Movie>();
lst.add(new Movie("move1", "genre1"));
System.out.println("List Check :" + lst.get(0).getName() + ":"
+ lst.size());
}
}
class Movie
{
private String name;
private String genre;
public Movie(String name, String genre)
{
name = this.name;
genre = this.genre;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getGenre()
{
return genre;
}
public void setGenre(String genre)
{
this.genre = genre;
}
}
This is wrong:
public Movie(String name, String genre)
{
name = this.name;
genre = this.genre;
}
should be
public Movie(String name, String genre)
{
this.name = name;
this.genre = genre;
}
like in the setters.
You are assigning parameters using this.name should be other way around
public Movie(String name, String genre)
{
this.name = name;
this.genre = genre;
}
your constructor is wrong, it should be
public Movie(String name, String genre)
{
this.name = name;
this.genre = genre;
}
The local variables, name and genre are being assigned to the global variable names of the same name in the constructor of Movie. The default value of Object types is null so these variables remain unassigned. The corrected constructor should appear as
public Movie(String name, String genre) {
this.name = name;
this.genre = genre;
}
Reimeus has it right.
The "this" refers to the class itself, so "this.genre" would refer to the class variable "genre".
Switch them around to fix the problem.
When you write name = this.name, you are assigning the value of the this.name to name. So in your case, this.name holds null when initialised and you are assigning it to name.
It is a good practice to use the getters and setters that you have written in your bean.
you can set it like setName(name) instead of writing this.name=name. Both eventually perform the same action though.

Categories