sunleo
sunleo

Reputation: 10943

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

}

Upvotes: 0

Views: 118

Answers (6)

Reimeus
Reimeus

Reputation: 159754

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

Upvotes: 1

Adarsh
Adarsh

Reputation: 3641

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.

Upvotes: 0

Bob Stout
Bob Stout

Reputation: 1259

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.

Upvotes: 0

user902383
user902383

Reputation: 8640

your constructor is wrong, it should be

public Movie(String name, String genre)
{
    this.name = name;
    this.genre = genre;
}

Upvotes: 1

Laksitha Ranasingha
Laksitha Ranasingha

Reputation: 4507

You are assigning parameters using this.name should be other way around

public Movie(String name, String genre)
{
    this.name = name;
    this.genre = genre;
}

Upvotes: 1

Kai
Kai

Reputation: 39641

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.

Upvotes: 4

Related Questions