Get values from arraylist java? - java

I have the following class
public class Patient implements Serializable {
private int id;
private String name;
private String desc;
public Patient(int id, String name, String desc) {
this.id = id;
this.name = name;
this.desc=desc;
}
And then the following getter and setter methods in this class.
Declaring the arraylist
ArrayList<Patient> list = new ArrayList<Patient>();
Adding run time data in the list
list.add(new Patient(id++, name.getText(), disDesc.getText())
Now i want the read the elements stored in the list
How can i do that?
System.out.println(list.get(0));
I use this but it returns the object address of the class

You have to override the toString() method of Patient. There, you will return all information on the Patient object that you want to display.
Example: (my personal favorite)
private static final String SEPARATOR = ", ";
#Override
public String toString()
{
StringBuilder builder = new StringBuilder();
builder.append("ID: ").append(id).append(SEPARATOR);
builder.append("Name: ").append(name).append(SEPARATOR);
builder.append("Desc: ").append(desc);
return builder.toString();
}
Example 2:
#Override
public String toString()
{
return "ID: " + id + ", Name: " + name + ", Desc: " + desc;
}
Example 3:
#Override
public String toString()
{
return MessageFormat.format("ID: {0}, Name: {1}, Desc: {2}", id, name, desc);
}
Use either one. It is a matter of preference.

You have to cast the element,
((Patient) list.get(0)).getName();
And you must add a public getter method to your Patient class.

Related

trying to call superclass method in subclass

Probably a pretty noob question, but I cant figure it out. I have a class Person to store a name that is input from the keyboard
public class Person {
private String firstName;
private String lastName;
public Person()
{
firstName = "";
lastName = "";
}
public Person(String first, String last)
{
setName(first, last);
}
public String toString()
{
return(firstName + " " + lastName);
}
public void setName(String first, String last)
{
firstName = first;
lastName = last;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
}
I am trying to call the toString method in a subclass called Patient
public class Patient extends Person {
private int patientID, patientAge;
public Patient()
{
patientID = 0; //for a different part of the class that works
patientAge = 0;
}
#Override
public String toString()
{
return ("Patient Name: "+super.toString());
}
}
I cannot get it to output the name in main when I call the toString method from the Patient class, but when I tested it, it output the name when I call the toString method from the Person class.
The method call in main looks like Patient pnt = new Patient(); System.out.print(Pnt.toString());
it prints out in the console "Patient Name: ". Any feedback on what I am doing wrong or ideas on how to get it to work
Here:
public Person()
{
firstName = "";
lastName = "";
}
Your subclass is missing a reasonable call to a super class constructor. So when you instantiate your Patient objects, the above constructor is used, and all patients end up with "" as first and last name!
When you create a Patient, then a patient should have a name, too! But your constructor in Patient only sets the Patient related fields. And implicitly, the default super constructor is called. Therefore the Person fields are all set to be empty strings!
A much better approach would look like this:
class Person {
private final String firstName;
... lastName
public Person(String firstName, String lastName) {
this.firstName = firstName;
...
and then
class Patient extends Person {
private final int patientID;
public Patient(int patientID, String firstName, String lastName) {
super(firstName, lastName);
this.patientID = patientID;
)
Why is that better: names and IDs don't change (normally). There is no point in having getters for them. You create your object once, and then that data is fixed! There is also no point in having that default constructor in Person. A person with empty names doesn't make sense. Thus: don't create a class that allows you to create "invalid" objects. Your classes model reality. There are no real people without names!
And one other hint: use #Override when overriding methods, so that the compiler can tell you when you get something wrong!
if the problem is to output the name in main when you call the toString method from the Patient class, I think the code bellow will help you.
have you tried to construct the Patient object like this?
public static void main(String[] args) {
Patient p = new Patient();
System.out.println(p.toString());
}
Actually I do not see problem in your code.
Person person = new Person();
person.setName("aa", "bb");
System.out.println(person); // aa bb
Patient patient = new Patient();
patient.setName("cc", "dd");
System.out.println(patient); // Patient Name: cc dd
I think that you set name wrong pr use not correct reference. Check it.
You don't have any constructor for your PATIENT subclass. You don't set any firstName or lastName to any patient.
To keep familiar constructor as you used in your parent class, tru to use:
public Patient() {
super("default_firstName", "default_lastName");
this.patientID = 0;
this.patientAge = 0;
}
public Patient(String firstName, String lastName, int patientAge) {
super(firstName, lastName);
this.patientID = 0; //can be implemented some method for automatically setting numbers
this.patientAge = patientAge;
}
This way you always get firstName and lastName even if constructor will be called empty.
According to you toString method, it's correct and it call super class method:
#Override
public String toString()
{
return("Patient name is "+super.toString());
}
But notice that you return STRING value so to make it visible on the screen remember to use:
System.out.println(patient.toString());
Then it will be visible :)
I have added some comments and code in your Person class that should fix your issues.
public class Person {
private String firstName; //store the first name
private String lastName; //sore the last name
//initialize firstName and lastName to an empty string
public Person() {
firstName = "";
lastName = "";
}
//set firstname and lastname according to the parameters.
public Person(String first, String last) {
//setName(first, last); remove this crap.
// Use the contructor properly when initialize your person object. Like this:
this.firstName = first;
this.lastName = last;
}
//method to output the first name and last name
#Override
public String toString() {
return (firstName + " " + lastName);
}
//method to set firstName and lastName according to the paramters
public void setName(String first, String last) {
//
firstName = first;
lastName = last;
}
}

Best way to access an object stored in an ArrayList?

I have a Student class that contains an ArrayList of type Course, and Course is class with some fields like className, classTime, etc along with the appropriate getters and setters. Say I created an ArrayList of Course and have stored it into the Student class.
How can I for example print the className of a particular Course object (which is stored in an ArrayList stored in the Student class)?
So far I tried this, below is part of the code for class Student:
class Student {
ArrayList<Course> studentSchedule;
public ArrayList<Course> getStudentSchedule() {
return studentSchedule;
}
public void setStudentSchedule(ArrayList<Course> studentSchedule) {
this.studentSchedule = studentSchedule;
}
}
Then I have some code that created student1 of type Student and stored an ArrayList of Course into it.
Say I want to access the className in the first object in the ArrayList that's in student1. So far I have this and it works... is it fine?
ArrayList<Course> schedule = student1.getStudentSchedule();
System.out.print("\n course name at position 0 is " +
student1.getStudentScheduleClassName(0));
It feels weird to create another Arraylist just for this purpose... but then I thought since in line 1, schedule will only contain the addresses that point to the location and shouldn't take much space?
Is there a more appropriate way to do this?
Based on above discussion I tried to complete the solution for my reference.
import java.util.ArrayList;
import java.util.Iterator;
public class ListExample {
public static void main(String[] args) {
Student student1 = new Student();
ArrayList<Course> student1Schedule = new ArrayList<Course>();
student1Schedule.add(new Course("Computer Science", "Training Room"));
student1Schedule.add(new Course("Mobile App Development", "Training Room 2"));
student1.setStudentSchedule(student1Schedule);
// Prints only one course
System.out.println(" ** Course" + student1.getStudentSchedule().get(0).toString());
// Print all the courses attended by the student
ArrayList<Course> studentDetails = student1.getStudentSchedule();
Iterator<Course> studentIterator = studentDetails.iterator();
while (studentIterator.hasNext()) {
Course courseName = studentIterator.next();
System.out.println(courseName);
}
}
static class Student {
private ArrayList<Course> studentSchedule;
public ArrayList<Course> getStudentSchedule() {
return studentSchedule;
}
public void setStudentSchedule(ArrayList<Course> studentSchedule) {
this.studentSchedule = studentSchedule;
}
}
static class Course {
private String courseName;
private String className;
public Course (String courseName, String className){
this.className =className;
this.courseName = courseName;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String toString (){
return "Course Name :" + this.courseName + "\n" + "Class Name : " + className + "\n";
}
}
}
public class Course{
private String className;
public String getClassName(){
return className;
}
public void setClassName(String c){
className =c;
}
}
So when you have this you can simply do
System.out.println(student1.getStudentSchedule().get(0).getClassName())
Make className into an instance variable of Course and have getter and setter methods within the Course for the class name. Then you will print out the class name.
You can access the first course's class name as:
System.out.print("\n course name at position 0 is " + schedule.get(0).getClassName());
since you've already defined getter/setter in the Course class as you mentioned.

Wondering if I'm doing this immutability exercise correctly

My professor just went over mutable and immutable, and gave us this coding exercise to complete.
1) Create a Customer object called customer with initial values of 1 and "Cust1"
respectively.
2) Display the customer object to the screen using the toString() method.
3) Create a String object reference called name and assign to it the customer's name.
4) Assign the value "Bo Beep" to the object reference name.
5) Display the customer object to the screen using the toString() method.
The output should look like this.
Customer{id=1, name=Cust1}
Customer{id=1, name=Cust1}
I currently have 2 seperate classes, here they are. I'm not sure whether I'm doing it correctly, I think I have done the first 2 right, but I'm not sure about 3-5.
Any input is helpful, thanks!
Here's my main class,
package hw01;
public class Main {
static Customer customer = new Customer(1, "cust1");
static Customer name = new Customer(1, "Bo Peep");
public static void main(String[] args) {
System.out.println(customer);
System.out.print(customer);
}
}
And here's my Customer class.
package hw01;
public class Customer {
private int id;
private String name;
public Customer() {
}
public Customer(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
#Override
public String toString() {
return "Customer{" + "id=" + id + ", name=" + name + '}';
}
}
Sounds like for #3 it should be something like this:
String name = customer.getName();
and then #4 would be:
name = "Bo Peep";
The goal of the exercise I think is to demonstrate that even though name and customer.name reference the same String object, since a String is immutable when you set name = "Bo Peep"; you're not changing the actual String object but instead creating and referencing a new String object. If the String were mutable then printing the customer the 2nd time would display the name "Bo Peep".

toString method

I want to add a toString method in the Item class that returns the title of the item in there.
I have need make sure that the toString method in the DVD class calls the toString method in Item so that it can return a string that contains both the title and the director.
Item is the superclass and DVD is the subclass.
public class Item
{
private String title;
private int playingTime;
private boolean gotIt;
private String comment;
public Item(String theTitle, int time)
{
title = theTitle;
playingTime = time;
gotIt = false;
comment = "<no comment>";
}
// Getters and setters omitted
public void print()
{
System.out.print(title + " (" + playingTime + " mins)");
if(gotIt) {
System.out.println("*");
} else {
System.out.println();
}
System.out.println(" " + comment);
}
}
public class DVD extends Item
{
private String director;
public DVD(String theTitle, String theDirector, int time)
{
super(theTitle, time);
director = theDirector;
}
// Getters and setters omitted
public void print()
{
System.out.println(" director: " + director);
}
}
Item toString:
public String toString()
{
return title;
}
DVD toString:
public String toString()
{
return super.toString() + " director: " + director;
}
Also, I don't know what you're trying to do with this but I would put those print() methods in these classes.
You will be better of returning the string representation and printing it somewhere else (with this you can test this class without mocking System.out)
Cheers
A toString method is already defined in each Java class (it inherits the toString of Object). But it will return a practically meaningless value (AFAIR, the internal address/id of the instance within the JDK - I might be wrong).
What you need to do is to override that method and make it return a String that is the title of the Item. For the DVD class, you have to override toString and make it a string made up of the concatenation of the title and director.
For the Item class, your method should look something like this:
public String toString(){
return this.title;
}
You should be able to use the same idea to implement toString for DVD.

find a keyword in a collection and return it

I have a collection i added CD, DVD, book information into hashsets.
Each one has a keyword and i would like to do a search for a specific keyword and return the specific book,CD,dvd... heres the output to give you an idea..
-Book-
Author: Robert A. Heinlein
# pages 325
title: Starship Troopers
keywords: [science fiction, war, weapons]
-Music-
band: Grateful Dead
# songs: 12
members: [Jerry Garcia, Bill Kreutzman, Keith Godcheaux]
title: Europe In '72
keywords: [acid rock, sixties, jam bands]
-Movie-
director: Sofia Coppola
# scenes: 14
cast: [Bill Murray, Scarlett Johansson]
title: Lost In Translation
keywords: [Japan, loneliness]
>>> items for keyword: science fiction
none
>>> items for keyword: jam bands
none
C:\Java\a03>
I have 3 classes.
Main()
Library - this is where i do all the adding of cd, DVD, books. lookups, etc
Items class(CD class, DVd class, book class) using inheritance..
in main() i am sending in information to the library class to add to the sets.
then i print out all the books, cd, movies just added.
then i do a lookup for a specific keyword.
And this is where i am having problems. i wrote a getkeyword function in CD, DVD, book class.
What i want to do is get the keyword and then see if they match and then return it as a collection.
here is main() i will only show some of it to keep this short - i will not show you how i am adding since it works good..
printItemsForKeyword(out, "science fiction");
printItemsForKeyword(out, "jam bands");
printItemsForKeyword(out, "xxx");
private static void printItemsForKeyword (PrintStream out, String keyword)
{
Collection<Item> items;
out.printf(">>> items for keyword: %s\n\n", keyword);
items = library.itemsForKeyword(keyword);
printItems(out, items);
}
now here in the library class is where i need help
in the itemsForKeyword(String keyword) function...
so, the first thing i am trying to find is "Science Fiction"
I think i need to cast item since item has the CD, DVD, book classes and i need to return a colection???
right now i am trying to return key and it wont since its incompatable with the return.
public class Library
{
private Set<Item> theCDs = new HashSet<Item>();
private Set<Item> theDVDs = new HashSet<Item>();
private Set<Item> theBooks = new HashSet<Item>();
public Collection<Item> itemsForKeyword(String keyword)
{
Item key = new Item();
((CD)key).getKeyword(); // i dont think i am even doing this right
if(key.equals(keyword))
{
return key; // cant return key
}
return null;
}
I did define a getKeywords() function in each of the classes below.
Here is the Items class since you will need to look it over..
import java.io.PrintStream;
import java.util.Collection;
import java.util.*;
class Item
{
private String title;
public String toString()
{
String line1 = "title: " + title + "\n";
return line1;
}
public void print()
{
System.out.println(toString());
}
public Item()
{
}
public Item(String theTitle)
{
title = theTitle;
}
public String getTitle()
{
return title;
}
}
class CD extends Item
{
private String artist;
private String [] members;
private String [] keywords;
private int number;
public CD(String theTitle, String theBand, int Snumber, String... keywords)
{
super(theTitle);
this.artist = theBand;
this.number = Snumber;
this.keywords = keywords;
}
public void addband(String... member)
{
this.members = member;
}
public String getArtist()
{
return artist;
}
public String [] getMembers()
{
return members;
}
public String [] getKeyword()
{
return keywords;
}
public String toString()
{
return "-Music-" + "\n"
+ "band: " + artist + "\n"
+ "# songs: " + number + "\n"
+ "members: " + Arrays.toString(members)
+ "\n" + super.toString()
+ "keywords: " + Arrays.toString(keywords)
+ "\n" + "\n" ;
}
public void print()
{
System.out.println(toString());
}
}
class DVD extends Item
{
private String director;
private String [] cast;
private int scenes;
private String [] keywords;
public DVD(String theTitle, String theDirector, int nScenes, String... keywords)
{
super(theTitle);
this.director = theDirector;
this.scenes = nScenes;
this.keywords = keywords;
}
public void addmoviecast(String... members)
{
this.cast = members;
}
public String [] getCast()
{
return cast;
}
public String getDirector()
{
return director;
}
public String [] getKeyword()
{
return keywords;
}
public String toString()
{
return "-Movie-" + "\n"
+ "director: " + director + "\n"
+ "# scenes: " + scenes + "\n"
+ "cast: " + Arrays.toString(cast) + "\n"
+ super.toString()
+ "keywords: " + Arrays.toString(keywords)
+ "\n" + "\n" ;
}
public void print()
{
System.out.println(toString());
}
}
class Book extends Item
{
private String author;
private int pages;
private String [] keywords;
public Book(String theTitle, String theAuthor, int nPages, String... keywords)
{
super(theTitle);
this.author = theAuthor;
this.pages = nPages;
this.keywords = keywords;
}
public String getAuthor()
{
return author;
}
public String [] getKeyword()
{
return keywords;
}
public void print()
{
System.out.println(toString());
}
public String toString()
{
return "-Book-" + "\n"
+ "Author: " + author + "\n"
+ "# pages " + pages + "\n"
+ super.toString()
+ "keywords: " + Arrays.toString(keywords)
+ "\n" + "\n" ;
}
}
the reason why i think i need to do sometype of cast is because i had to when i added
bandmembers..
public void addBandMembers(Item musicCD, String... members)
{
((CD)musicCD).addband(members);
}
So, what can i do to find a keyword in the items and return those?
would it be better to look directly at the sets and do some type of cast to get it to return? im just stumped..
Thank you..
Create an index (SortedMap<String, List<Item>>) relating keywords to the items they represent. When an object is added to the library, map it to each of its keywords in the index, adding new keywords as needed. Search the index to find the objects.
It's a little hard to follow what you're trying to ask, but I hope the following is what you're after. It looks to me that you're chiefly concerned with getting a Collection of Items, which you want done using the method public Collection<Item> itemsForKeyword(String keyword).
In this method, you should do the following:
Create an empty Collection (either a HashSet or TreeSet depending on whether you need it sorted).
Loop through theCDs. For each Item, get its keywords.
Loop through keywords. If you find one that equals (or equalsIgnoreCase) the one passed in, add the Item to the Collection you created in 1.
Repeat 2 and 3 for theDVDs and theBooks.
Return the Collection you created in 1.
A couple of other things:
I'd suggest that you rename getKeyword to getKeywords, since that's what it's returning.
For the purposes of this method, you would be better off having keywords in a HashSet so that you can do item.getKeyword().containsKey(keyword) instead of the looping in 3. If you do this and need it the method to be case insensitive, you would need to store keywords in all lower case or all upper case, and add in a step 0 to convert the passed in keyword to the correct case before searching. Also, this may not be the way to go if you need to extensively use keywords as an array elsewhere.

Categories