ArrayList Java Addition - java

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.

Related

How to access the fields of an object in java?

I apologize, this question has already been answered once. However, the solution didn't help me.
I made a program working with an ArrayList containing name,ID and country. However, I cannot access the name, ID and country on their own, only their object as a whole. I tried using animal.name and I get the error name cannot be resolved or is not a field. I tried using methods like getName() to return the name of the object, but I got the error The method getName() is undefined for the type ArrayList<ANIMAL>. Would you please help me with that?
This is the class which, when called, creates a new object inside the ArrayList and fields of which I'm trying to access:
import java.io.*;
public class ANIMAL implements Serializable {
String nameA;
String IDA;
String countryA;
public ANIMAL(String name, String ID, String country){
nameA = name;
String IDA = ID;
String countryA = country;
}
public String getName(){
return nameA;
}
public String getCountry(){
return countryA;
}
public String getID(){
return IDA;
}
}
Your animal class:
public class Animal {
private String name;
private String id;
private String country;
public Animal (String name, String id, String country){
this.name = name;
this.id = id;
this.country = country;
}
public String getName(){
return name;
}
public String getCountry(){
return country;
}
public String getId(){
return id;
}
}
Pseudo application class (with main method for starting the application):
public class MyApp {
public static void main(String[] args) {
List<Animal> list = new ArrayList<>();
list.add(new Animal("British Bulldog", "12345", "UK"));
list.add(new Animal("Boston Terrier", "12346", "USA"));
list.add(new Animal("German Shepherd", "12347", "Germany"));
// this is a for-each loop but basically you just need
// to get an item from the list, list.get(i) would suffice
for (Animal a: list) {
System.out.println(a.getName());
}
}
}
Prints:
British Bulldog
Boston Terrier
German Shepherd
Also: I took the liberty of tidying up your code to match conventions, look at the differences and try to understand them.
Your constructor was flawed.
import java.io.*;
public class ANIMAL implements Serializable {
String name;
String ID;
String country;
public ANIMAL(String name, String ID, String country){
this.name = name;
this.ID = ID;
// String IDA = ID; doesn't assigns param ID to field ID of the class
this.country = country; //same
}
public String getName(){
return name;
}
public String getCountry(){
return country;
}
public String getID(){
return ID;
}
}
Hope this helps.

Java remove User defined object from Tree Set

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);
}
}

Is possible to set a default value and then change the value in a constructor

class Person {
private String name;
private String sex="male";
public Person(String name) {
this.name = name;
}
public String getSex(){return this.sex;}
}
In the above class, if I want to set the default value for sex. is it OK?
then, if I want to create new Person, is the following code good?
Person p = new Person("mike");
String sex = p.getSex();
You can chain constructors in Java to give certain values defaults.
For example, here's a constructor that takes a name and one that takes a name and a sex.
public class Person {
private String name;
private String sex;
public Person(String name, String sex) {
this.name = name;
this.sex = sex;
}
public Person(String name) {
this(name, "male");
}
// getters/setters here
}
If your object has a lot of properties that may be optional, you should consider the Builder pattern instead of standard constructors.
It always to good to make your class thread safe by defining the fields as final and assign the values only through constructor.
class Person {
private final String name;
private final String sex;
public Person(String name, String sex) {
this.name = name;
this.sex = sex;
}
public String getName() { return this.name; }
public String getSex(){return this.sex;}
}

java creating an object in subclass

Having trouble creating an author object in the Book class.This is indeed Homework, I have came up with all the methods on my own and have been staring at this assignment for 2 hours now. any tips hints will be appreciated. I believe I am only allowed this one Author constructor with 3 parameters otherwise I would just have made an Author constructor with no arguments and the problem would be gone.
public class Author {
protected String name;
protected String email;
protected char gender;
public Author(String name, String email, char gender)
{
this.name = name;
this.email = email;
this.gender = gender;
}
public String getName()
{
return name;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public char getGener()
{
return gender;
}
public String toString()
{
return ( name + "(" + gender + ")#" + email);
}
}
public class Book extends Author{
private String name;
private Author author;
private double price;
private int qtyInStock = 0;
public Book(String name, Author author,Double price)
{
this.author = new author;
this.name = name;
this.price = price;
}
public Book(String name, Author author, double price, int qtyInStock)
{
this.name = name;
this.author = author;
this.price = price;
this.qtyInStock = qtyInStock;
}
public String getName()
{
return name;
}
public Author getAuthor()
{
return author;
}
public double getPrice()
{
return price;
}
public void setPrice(double price)
{
this.price = price;
}
public int getQtyInStock()
{
return qtyInStock;
}
public void setQtyInStock(int qtyInStock)
{
this.qtyInStock = qtyInStock;
}
public String toString()
{
return (name + " by " + author + "(" + super.gender + ")at" + super.email);
}
}
It should be this.author = author; without the new keyword.
You are assigning the Author object in the constructor, not creating new one.
By the way, Book inherits from Author which means it already has the Author functionality. You don't have to save it as member.
Seems strange that Book extends Author. A Book is not an Author.
I think what you want to do is create a Book object that has an Author, but you are already passing in an Author to your Book constructor, so what is the problem?
class Book {
public Book(String title, Author author) {
this.title = title;
this.author = author;
}
}
If you're wondering how to create the Author, just create it before you pass it to the Book.
Author author = new Author("bob", "bob#email.com", 'm');
Book book = new Book("some title", author);
Does that make sense?
You are inheriting Author in Book, inheritance is is a relationship, means Book is a Author which is not true in real world scenario , you need has a relation which makes sense , that Book has a Author.
So don't extend author in Book , keep a field of author in it as you have already did. Change you design.
There are multiple mistakes in your code:
as #Guy said, you need to assign the author with this.author = author, without the new keyword.
you are shadowing the name variable from the Author class by also including a variable with the same name in the Book class. Remove that variable and the getter and setter methods from the Book class.
You donĀ“t have a no parameter constructor, so you have to call the parent constructor in your Book class by calling super(name, email, gender);.
you should replace new author with author, also when you call the constructor of a sub Type, the Parent class's default constructor is invoked by default. so you need to specify a default constructor in your parent class, or to prevent this explicitly call your parametric constructor of parent class in the child class constructor .
Besides changing tothis.author = author.
You also need to add super(name, name, 'M'); to the two constructors of the Book class.
public class Book extends Author{
private String name;
//private final String email;
// private char gender;
private Author author;// = new Author(name,super.email,super.gender);
private double price;
private int qtyInStock = 0;
public Book(String name, Author author,double price)
{
//super();
this.author = author;// new Author(name,super.email,super.gender);
super.name = author.getName();
super.gender = author.getGender();
super.email = author.getEmail();
this.name = name;
this.price = price;
}
public Book(String name, Author author, double price, int qtyInStock)
{
this.author = author;
super.name = author.getName();
super.gender = author.getGender();
super.email = author.getEmail();
this.name = name;
this.price = price;
this.qtyInStock = qtyInStock;
}
public String getName()
{
return name;
}
public Author getAuthor()
{
return author;
}
public double getPrice()
{
return price;
}
public void setPrice(double price)
{
this.price = price;
}
public int getQtyInStock()
{
return qtyInStock;
}
public void setQtyInStock(int qtyInStock)
{
this.qtyInStock = qtyInStock;
}
public String toString()
{
return (super.name + " by " + this.name + "(" + super.gender + ")at" + super.email);
}
also added this to the author class
public Author()
{
}

Enum error in FreeMarker template

I have the following
public enum Gender {MALE, FEMALE}
and
public class Person {
private String name;
private Gender gender;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
}
In a FreeMarker termplate ${person.name} works fine, but ${person.gender} gives Expression person.gender is undefined on ....
Any idea why?
user person.gender.MALE or person.gender.FEMALE
The problem was when the method getGender was returning null. Although the error message is not intuitive.

Categories