Print Different Object Data From ArrayList in Java - java

Is there some way to print different data from an ArrayList containing different objects?
For example, I created two basic classes:
import java.util.*;
class Furniture{
String name;
int weight;
Furniture(String name, int weight){
this.name = name;
this.weight = weight;
}
String getName(){
return name;
}
int getWeight(){
return weight;
}
}
}
class Resident{
String name;
Resident(String name){
this.name = name;
}
String getName(){
return name;
}
}
Then I stored them in an ArrayList<Object> and wanted to print the names, by using declared below printArrayList method:
public class Main{
public static <E> void printArrayList(ArrayList<E> arrayToPrint){
for(E element : arrayToPrint){
try{
System.out.println(element.getName());
}
catch(Exception e){
System.out.println("Exception e: " + e);
}
}
}
public static void main(String []args){
Furniture sofa = new Furniture("Sofa", 5);
Resident mike = new Resident("Mike");
ArrayList<Object> arrayList = new ArrayList<>();
arrayList.add(sofa);
arrayList.add(mike);
printArrayList(arrayList);
}
Now, I know that not all objects can have a variable name or declared get method, therefore I tried to exclude these cases by try/catch.
I also tried to exclude it by using fe:
if(elements.getName() == null)
Still, same results.

You don't need to use a parameterized type. Rather introduce a specific interface (for example NameAware) that exposes the getName() method that your classes with implement. In this way you could rely on a common type.
public interface NameAware{
String getName();
}
public class Resident implements NameAware{
...
public String getName(){
return name;
}
}
public class Furniture implements NameAware{
...
public String getName(){
return name;
}
}
And define your method as :
public static void printArrayList(ArrayList<NameAware> arrayToPrint) {
for (NameAware element : arrayToPrint) {
try {
System.out.println(element.getName());
} catch (Exception e) {
System.out.println("Exception e: " + e);
}
}
}
Note that you should change your actual code from :
ArrayList<Object> arrayList = new ArrayList<>();
to
ArrayList<NameAware> arrayList = new ArrayList<>();

The best practice would be to declare an interface with the getName method, and have both Furniture and Resident implement it.
public interface Namable {
public String getName();
}
Then, use a List<Namable> instead of a List<Object>:
Furniture sofa = new Furniture("Sofa", 5);
Resident mike = new Resident("Mike");
List<Namable> arrayList = new ArrayList<>();
arrayList.add(sofa);
arrayList.add(mike);
for (Namable n : arrayList) {
System.out.println(n.getName());
}

Related

return a subclass-type in java

I have a subclass "OnlineCourse". It´s a subclass of "Course". I want to return "OnlineCourse" in my class "Student". But instead of "EIST" I get back null.
Here´s what I have:
public class Student {
public String matriculationNumber;
public String name;
public int age;
public Course study() {
TODO 4: Comment the code below back in
Change the Course type to OnlineCourse and set its
title to "EIST"
return the new course
// Course course = new Course();
// course.join();
// return course;
Course EIST = new OnlineCourse();
EIST.join();
return EIST;
}
}
Subclass that extends course and should be initiated as the return type for "EIST" in the class Student.
public class OnlineCourse extends Course{
public URL livestreamUrl;
public Course join() {
System.out.println("joined the course " + title);
return this;
}
public Course drop() {
System.out.println("dropped out of the course" + title);
return this;
}
}
public abstract class Course {
public String title;
public String description;
public LocalDate examDate;
public List<Lecture> lectures;
public abstract Course join();
public abstract Course drop();
}
Main- Method:
public class Main {
public static void main(String[] args) {
var student = new Student();
student.matriculationNumber = "01234567";
student.name = "Joe Doe";
student.age = 42;
student.study();
}
}
I think you're saying the course title is showing as null. In which case you have to set it for it to print. I'd also note that where you have EIST - that's just a variable name, it can be anything and doesn't have any affect on any values.
If I were to guess, I think you'd want something like this -
public static void main(String[] args) {
var student = new Student();
student.matriculationNumber = "01234567";
student.name = "Joe Doe";
student.age = 42;
student.study("EIST");
}
And in Course, you'd want a setter method for the title like, -
public setCourseTitle(String title) {
this.title = title;
}
And in Student
public Course study(String courseTitle) {
Course EISTCourse = new OnlineCourse();
EISTCourse.setCourseTitle(courseTitle);
EISTCourse.join();
return EISTCourse;
}

Why can't I accesses the properties of an object stored in a element of a ArrayList?

I have two packages lets give them the name package 1 and package 2.
Class A and Class B is in package1. Class A contains an ArrayList called PTable. Class B contains a function called query() that filters through PTable,in Class A, based on a certain conditions and returns an ArrayList called result that contains all the elements from PTable that meet that condition.
I now have package2 that contains Class C. Class C imports Class B from package 1; Class C is a subclass of HttpServlet. I create an object of Class B in class C and initializer it.
I then call the function query() and assign it to a variable called results. When I try and get the properties of an element at a certain index, I can't see the properties of the original objects stored in the ArrayList PTable.[This is what appears when I try and access the properties of the objects. My aim is to see the second image ][1]
Nice to ask questions but first spend sometime studying Java. Read a book or online and you will learn about casting very quickly. Also about classes, super classes etc
Your storing the objects in a variable of type Element (your results array list).
Cast the object back to the type it belongs too and then you will see the variables.
Code design note : storing different types of classesin the same array list is legal and possible but bug prone. Try to avoid it. If you change the order of storing variables into the list, you need to change all the access code too. Anyway happy learning.
There are free online Java tutorials study them -> https://www.google.co.in/search?q=java+tutorial+beginner
Sample class, in the main method try to get the object at position 1 and cast it to a Person :
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
super();
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Car {
private String manufacturer;
private String model;
private double price;
private int yearOfMfr;
private Date dateBought;
private String licenceNumber;
public Car() {
super();
}
public Car(String manufacturer, String model, double price, int yearOfMfr, Date dateBought, String licenceNumber) {
super();
this.manufacturer = manufacturer;
this.model = model;
this.price = price;
this.yearOfMfr = yearOfMfr;
this.dateBought = dateBought;
this.licenceNumber = licenceNumber;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getYearOfMfr() {
return yearOfMfr;
}
public void setYearOfMfr(int yearOfMfr) {
this.yearOfMfr = yearOfMfr;
}
public Date getDateBought() {
return dateBought;
}
public void setDateBought(Date dateBought) {
this.dateBought = dateBought;
}
public String getLicenceNumber() {
return licenceNumber;
}
public void setLicenceNumber(String licenceNumber) {
this.licenceNumber = licenceNumber;
}
}
public class DemoApp {
public static void main(String[] args) {
List<Object> results = new ArrayList<>();
DemoApp app = new DemoApp();
app.fillItUp(results);
Car acar = (Car) results.get(0);
acar.setLicenceNumber("Flying Duck");
}
private void fillItUp(List<Object> results) {
Car car = new Car("sel2in", "electric_VTOL", 540923, 2018, new Date(2018, 3, 32), "Skyprog");
results.add(car);
results.add(new Person("tushar", 39));
}
}

why setXXX() method is not overrinding?

I have super class called pojo. I have a subclass called ExtendPojo.
pojo.java
package com.java.pojo;
public class pojo {
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 getNumber() {
return number;
}
public void setNumber(long number) {
this.number = number;
}
public String toString() {
return "pojo [name=" + name + ", age=" + age + ", number=" + number + "]";
}
private String name;
private int age;
private long number;
}
ExtendPojo.java
package com.java.pojo;
public class ExtendPojo extends pojo{
public static void main(String[] args) {
pojo obj = new pojo();
obj.setName("santhosh");
ExtendPojo exObj = new ExtendPojo();
exObj.setName("mahesh");//It is not overriding
System.out.println(obj.getName());//it prints santhosh.
}
public void setName(String name){
super.setName(name);
}
}
You are creating two independent objects.
First you create an object and name it santhosh. This object is referenced by the obj variable.
pojo obj = new pojo();
obj.setName("santhosh");
Then you create a second object, which is referenced by the exObj variable.
ExtendPojo exObj = new ExtendPojo();
It doesn't have a name yet, since it's a new object and you haven't assigned the name. You then give it a name.
exObj.setName("mahesh");//It is not overriding
Now you print the name of the first object, which hasn't changed.
System.out.println(obj.getName());//it prints santhosh.
The code is doing exactly what you asked it to do.
If you intended the two variables to reference the same object, you'd do this:
ExtendPojo exObj = new ExtendPojo();
pojo obj = exObj ;//Same object, new variable, different type
obj.setName("santhosh");
exObj.setName("mahesh");//It is working now
System.out.println(obj.getName());//it prints mahesh.
I have gone through the Inheritance and method overriding concepts and clarified my doubts :)
public class ExtendPojo extends Pojo{
public static void main(String[] args) {
Pojo obj = new Pojo();
obj.setName("santhosh");
Pojo obj1 = new ExtendPojo();
obj1.setName("mahesh");//It is overriding now
System.out.println(obj1.getName());//it prints mahesh.
}
}

Finding and removing an object from arraylist while not knowing the object's variables

I'm new to Java and i've been bashing my head over the wall to solve this problem. Anyway below is a class that creates a Person and below that, is a class that creates a Phonebook using an ArrayList of type Person. I want to write the remove function (in order to remove a Person from the list) but my problem is that since i only get the name of the person i can't use the Indexof function (cause it requires object) to get at what position lies the name.
This is my first time using an ArrayList to store an Object so i'm not even sure
how my results would appear. I'm guessing that if the position of the name (in my list) is 10 then 11 would be the phone and 12 would be the address. Am i correct?
public class Person
{
private String name;
private String phone;
private String address;
public Person (String n, String p, String a)
{
this.name = n;
this.phone = p;
this.address = a;
}
public void setPhone(String newPhone)
{
this.phone = newPhone;
}
public String getName()
{
return this.name;
}
public String getPhone()
{
return this.phone;
}
public String getAddress()
{
return this.address;
}
public String print()
{
return "Name is : " + this.name + "\nPhone is : " + this.phone + "\nAddress is : " + this.address;
}
}
import java.util.*;
public class phoneBook
{
Scanner in = new Scanner ( System.in );
private ArrayList <Person> persons = new ArrayList <Person>();
private int i;
private boolean flag;
public void addPerson(Person p)
{
persons.add(p);
}
public void listPersons ()
{
System.out.println(persons);
}
public void lookUp (String theName)
{
flag = persons.contains(theName);
if ( flag == true )
{
System.out.println("That name exists!");
}
else
{
System.out.println("That name does not exist!");
}
}
public void remove (String theName)
{
}
Edit: I'm planning to use the Scanner in another function. Don't worry about it.
I'm not sure of if do you want to get the object of that array, but each object is indexed to that array (with full attributes), now you can remove it by using the following code,
public String removePerson(ArrayList<Person> arrayList,String name)
{
for(Person currentPerson:arrayList)
{
if(currentPerson.getName().equals(name))
{
arrayList.remove(currentPerson);
return "Removed successfully"
}
}
return "No record found for that person";
}
just pass the arrayList and the name of that person to this method
You should override the equals() and hashCode() methods in the Person class. This way you will define when two objects of this type will be considered equal. Then you can use list.contains(yourObject) to determine if that object is equal to any object in your list, this based on your equals() implementation.
Does this help you?
public void remove (String theName,ArrayList<Person> persons) {
for (int i = 0; i < persons.size();++i) {
if(persons[i].getName().equals(theName)) {
persons.remove(i);
}
}
}
Best regards, Nazar

Java List sort on object fields constant values

I have a enum representing severity level
public enum Severity {
HIGH("H"), MEDIUM("M"), LOW("L");
}
Person one = new Person();
one.setSeverity(Severity.HIGH);
other fields ...
Person two = new Person();
two.setSeverity(Severity.LOW);
.....
Person three = new Person();
three.setSeverity(Severity.HIGH);
List<Person> persons = Lists.newArrayList();
persons.add(one);
persons.add(two);
persons.add(three);
I would like to sort persons list to sort by severity field (i.e HIGH,MEDIUM then LOW).
My expected results after sorting the persons list should be in the order of HIGH,HIGH,LOW ?
can i know how i can achieve this ?
note : I am making use of com.google.common.collect
Try below code
Create an ENUM
package com.rais;
public enum Severity {
HIGH("H"), MEDIUM("M"), LOW("L");
private final String value;
private Severity(String value) {
this.value = value;
}
}
Now Create Person class according to your requirement eg.
package com.rais;
public class Person {
private Severity severity;
private String name;
public Person(Severity severity, String name) {
super();
this.severity = severity;
this.name = name;
}
public Severity getSeverity() {
return severity;
}
public void setSeverity(Severity severity) {
this.severity = severity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Finally create a Test Client and apply below logic.
package com.rais;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class TestClient {
public static void main(String[] args) {
Person one = new Person(Severity.HIGH, "shayam");
Person two = new Person(Severity.MEDIUM, "mohan");
Person three = new Person(Severity.LOW, "radha");
Person four = new Person(Severity.HIGH, "rakesh");
Person five = new Person(Severity.MEDIUM, "kailash");
Person six = new Person(Severity.LOW, "rais");
Person seven = new Person(Severity.LOW, "abhishek");
List<Person> persons = new ArrayList<Person>();
persons.add(one);
persons.add(two);
persons.add(three);
persons.add(four);
persons.add(five);
persons.add(six);
persons.add(seven);
Collections.sort(persons, new Comparator<Person>() {
#Override
public int compare(Person person1, Person person2) {
if(person1.getSeverity()==person2.getSeverity())
{
return person1.getName().compareTo(person2.getName());
}
else{
return person1.getSeverity().compareTo(person2.getSeverity());
}
}
});
for (Person person : persons) {
System.out.println(person.getName()+" "+ person.getSeverity());
}
}
}
I am sure you will get below output.
rakesh HIGH
shayam HIGH
kailash MEDIUM
mohan MEDIUM
abhishek LOW
radha LOW
rais LOW
Use Comparable or comparator and then apply
Collection.sort().
if using comparable interface you have to implement compareTo method and
Collection.sort(<list>)
and if using comparator then you have to override compareTo method and
Collection.sort(<list>, <comparator>)
and when to use comparatot or comparable read link:
http://iandjava.blogspot.in/2012/10/comparable-and-comparator.html
If you are using Google Collections, upgrade to Google Guava. Use its ComparisonChain class. Are you sure you want HIGH, MEDIUM, LOW in that order? The reverse fits Java comparisons better.
How do Persons have a severity level? Perhaps your class deserves a better name.
I would make Person implement Comparable, which makes the sorting code very simple and brief.
Note that enums are implicitly Comparable:
public enum Severity {
HIGH("H"), MEDIUM("M"), LOW("L");
private final String code;
private Severity(String code) {
this.code = code;
}
public String getCode() {
return code;
}
}
public class Person implements Comparable<Person> {
private Severity severity;
private final String name;
public Person(Severity severity, String name) {
this.severity = severity;
this.name = name;
}
public Severity getSeverity() {
return severity;
}
public void setSeverity(Severity severity) {
this.severity = severity;
}
public String getName() {
return name;
}
#Override
public int compareTo(Person person) {
return severity == person.severity ? name.compareTo(person.name)
: severity.compareTo(person.severity);
}
#Override
public String toString() {
return name + "(" + severity +")";
}
}
Now some test code:
Person one = new Person(Severity.HIGH, "one");
Person two = new Person(Severity.LOW, "two");
Person three = new Person(Severity.HIGH, "three");
List<Person> persons = new ArrayList<Person>();
persons.add(one);
persons.add(two);
persons.add(three);
Collections.sort(persons);
System.out.println(persons);
Output:
[one(HIGH), three(HIGH), two(LOW)]

Categories