This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 4 years ago.
i want to print all elements of my array list. Eclipse does not show an error, but it doesnt show the elements that i added in console. Can you please tell me what i did wrong?
The console shows:
Typ:Droide
ID:8282
NameR2D2
HumanoiderRoboter#15db9742
HumanoiderRoboter#6d06d69c
HumanoiderRoboter#7852e922
HumanoiderRoboter#4e25154f
Roboter Class:
public class Roboter {
protected String Name;
protected int ID;
protected String typ;
public Roboter(String Name, int ID, String typ) {
super();
this.Name = Name;
this.ID = ID;
this.typ = typ;
}
public void ausgebenNeu() {
System.out.println("ID:"+ID);
System.out.println("Name:"+Name);
System.out.println("Typ:"+typ);
}
HumanoiderRoboter Class:
import java.util.ArrayList;
public class HumanoiderRoboter extends Roboter {
String RoboterTyp;
public HumanoiderRoboter (String Name, int ID, String typ) {
super(Name, ID, typ);
}
public void ausgeben() {
ArrayList<HumanoiderRoboter> Sensoren = new ArrayList<HumanoiderRoboter>();
Sensoren.add(new HumanoiderRoboter("Sensor1", 4232, "Infrarotsensor"));
Sensoren.add(new HumanoiderRoboter("Sensor2", 9232, "Lichtsensor"));
Sensoren.add(new HumanoiderRoboter("Sensor3", 5777, "Touchssensor"));
Sensoren.add(new HumanoiderRoboter("Sensor4", 3321, "Gyrosensor"));
System.out.println("Typ:" + typ);
System.out.println("ID:" + ID);
System.out.println("Name" + Name);
for (Roboter ele : Sensoren) {
System.out.println(ele);
}
}
public static void main(String[] args) {
HumanoiderRoboter R2 = new HumanoiderRoboter("R2D2", 8282, "Droide");
R2.ausgeben();
}
}
Currently your problem is the HumanoiderRoboter doesn't overwrite the toString method which results the HumanoiderRoboter#4e25154f stuff. So if you overwrite the toString method it will print your object stuff you put in there:
...
#Override
public String toString() {
return "Typ: " + type + ", ID: " + id + ", Name: " + name;
}
...
Default toString method from Object looks like that:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
So now if you do System.out.println(theObject) it will for example result something like this:
Typ: some, ID: 5, Name: NiceRoboter
And if you want the complete array as one String you can use the Arrays#toString method:
System.out.println(Arrays.toString(yourList.toArray()));
In your Roboter class override toString() method like this:
public class Roboter {
//-----member fields,methods
//Add this method
#Override
public String toString(){
return "{name:"+this.Name+"}";
}
}
Also read this link for naming convention to follow in Java https://www.geeksforgeeks.org/java-naming-conventions/
Override toString() method in Roboter class.
public class Test extends Roboter {
String RoboterTyp;
public Test(String Name, int ID, String typ) {
super(Name, ID, typ);
}
public void ausgeben() {
ArrayList<Test> Sensoren = new ArrayList<Test>();
Sensoren.add(new Test("Sensor1", 4232, "Infrarotsensor"));
Sensoren.add(new Test("Sensor2", 9232, "Lichtsensor"));
Sensoren.add(new Test("Sensor3", 5777, "Touchssensor"));
Sensoren.add(new Test("Sensor4", 3321, "Gyrosensor"));
System.out.println("Typ:" + typ);
System.out.println("ID:" + ID);
System.out.println("Name" + Name);
for (Roboter ele : Sensoren) {
System.out.println(ele);
}
}
public static void main(String[] args) {
Test R2 = new Test("R2D2", 8282, "Droide");
R2.ausgeben();
}
}
public class Roboter {
String Name;
int ID;
String typ;
public Roboter(String name, int iD, String typ) {
super();
Name = name;
ID = iD;
this.typ = typ;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
public String getTyp() {
return typ;
}
public void setTyp(String typ) {
this.typ = typ;
}
#Override
public String toString() {
return "Roboter [Name=" + Name + ", ID=" + ID + ", typ=" + typ + "]";
}
}
Related
I have two POJOs (Person.java and User.java) that contain similar information. See below:
public class Person {
private String first_name;
private String last_name;
private Integer age;
private Integer weight;
private Integer height;
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
}
public class User {
private String name_first;
private String name_last;
private Integer my_age;
private Integer my_weight;
private String social_security;
public String getName_first() {
return name_first;
}
public void setName_first(String name_first) {
this.name_first = name_first;
}
public String getName_last() {
return name_last;
}
public void setName_last(String name_last) {
this.name_last = name_last;
}
public Integer getMy_age() {
return my_age;
}
public void setMy_age(Integer my_age) {
this.my_age = my_age;
}
public Integer getMy_weight() {
return my_weight;
}
public void setMy_weight(Integer my_weight) {
this.my_weight = my_weight;
}
public String getSocial_security() {
return social_security;
}
public void setSocial_security(String social_security) {
this.social_security = social_security;
}
}
I have defined a mapping.json file as shown below using GSON.
{
"columnMap": [
{
"userColumn": "name_first",
"personColumn": "first_name"
},
{
"userColumn": "last_first",
"personColumn": "first_last"
},
{
"userColumn": "my_age",
"personColumn": "age"
},
{
"userColumn": "my_weight",
"personColumn": "weight"
}
]
}
public class Mapping {
private ArrayList<Pair> columnMap;
public Mapping(){
columnMap = new ArrayList<>();
}
public ArrayList<Pair> getColumnMap() {
return columnMap;
}
public void setColumnMap(ArrayList<Pair> columnMap) {
this.columnMap = columnMap;
}
}
I am writing a utility class helper function that converts between a Person and User object the mapped pairs.
public class Pair {
private String userColumn;
private String personColumn;
public String getUserColumn() {
return userColumn;
}
public void setUserColumn(String userColumn) {
this.userColumn = userColumn;
}
public String getPersonColumn() {
return personColumn;
}
public void setPersonColumn(String personColumn) {
this.personColumn = personColumn;
}
public static void main(String args[]){
}
}
My question is below:
As you can see the returnVal object is being set by me (the programmer) to convert from a User POJO to a Person POJO. How do I leverage the pre-defined mapping.json to do this? The reason I am asking is in the future, the mapping.json file may change (maybe the weight mapping no longer exists). So I am trying to avoid re-programming this Utility.userToPerson() function. How can I achieve this? I am thinking Java reflection is the way to go, but I would like to hear back from the Java community.
public class Utility {
public static Person userToPerson(User u){
Person returnVal = new Person();
returnVal.setAge(u.getMy_age()); // <-- Question How do I leverage mapping.json here?
returnVal.setFirst_name(u.getName_first());
returnVal.setLast_name(u.getName_last());
returnVal.setWeight(u.getMy_weight());
return returnVal;
}
}
You can introspect the beans (i.e. User and Person) for the field names and call corresponding getter from User to fetch the value. Later call corresponding setter in Person.
Here I have taken userToPersonFieldsMap for mapping the field, you can load mapping from JSON file and construct the map accordingly.
Important code section is the for loop, where it dynamically calls getter and setter and does the job.
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
public class UserToPersonMapper {
public static void main(String[] args) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
Map<String, String> userToPersonFieldsMap = new HashMap<>();
userToPersonFieldsMap.put("name_first", "first_name");
userToPersonFieldsMap.put("last_first", "first_last");
userToPersonFieldsMap.put("age", "personAge");
//existing user
User user = new User("Tony", "Stark", 20);
//new person - to be initialised with values from user
Person person = new Person();
for (Map.Entry<String, String> entry : userToPersonFieldsMap.entrySet()) {
Object userVal = new PropertyDescriptor(entry.getKey(), User.class).getReadMethod().invoke(user);
new PropertyDescriptor(entry.getValue(), Person.class).getWriteMethod().invoke(person, userVal);
}
System.out.println(user);
System.out.println(person);
}
}
class User {
private String name_first;
private String last_first;
private int age;
public User(String name_first, String last_first, int age) {
this.name_first = name_first;
this.last_first = last_first;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName_first() {
return name_first;
}
public String getLast_first() {
return last_first;
}
public void setName_first(String name_first) {
this.name_first = name_first;
}
public void setLast_first(String last_first) {
this.last_first = last_first;
}
#Override
public String toString() {
return "User{" +
"name_first='" + name_first + '\'' +
", last_first='" + last_first + '\'' +
", age=" + age +
'}';
}
}
class Person {
private String first_name;
private String first_last;
private int personAge;
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public void setFirst_last(String first_last) {
this.first_last = first_last;
}
public String getFirst_name() {
return first_name;
}
public String getFirst_last() {
return first_last;
}
public int getPersonAge() {
return personAge;
}
public void setPersonAge(int personAge) {
this.personAge = personAge;
}
#Override
public String toString() {
return "Person{" +
"first_name='" + first_name + '\'' +
", first_last='" + first_last + '\'' +
", personAge=" + personAge +
'}';
}
}
You can tweak and try it out this example to make it more align with your requirement.
Note:
This solution uses reflection.
I got 2 classes
class Curso{
private String name;
public Curso(String nome){
this.name = nome;
}
public String getName(){
return this.name;
}
}
and
public class testaCurso{
public static void main(String[] args){
Course c1 = new Course("Computer Science");
c1.addDisciplina("AlgProgII");
c1.addDisciplina("SO");
c1.addDisciplina ("Grafos");
System.out.println(c1);
}
}
i gotta modify the Course class so that it can store the names of the Disciplina that make up the course and work for the test above with the output as shown. Consider that a course will not have a maximum of 50 subjects.
output:
Course: Computer Science,
Disciplinas:{ AlgProgII SO Grafos }
class Curso {
private String name;
// Add an list field containg the disciplinas
private final List<String> disciplinas = new ArrayList<>();
public Curso(String name){
this.name = name;
}
public String getName(){
return this.name;
}
// Add a `addDisciplina` method
public void addDisciplina(String name) {
disciplinas.add(name);
}
// Override the `toString` method
#Override
public String toString() {
return "Course: " + name + ", Disciplinas: + ", disciplinas;
}
}
We can implement toString() like the following:
public class Course {
private final String name;
private final List<String> disciplinas;
public Course(String name){
this.name = name;
this.disciplinas = new ArrayList<>();
}
public Course(String name, List<String> disciplinas){
this.name = name;
this.disciplinas = new ArrayList<>(disciplinas);
}
public void addDisciplinas(String discplina){
this.disciplinas.add(discplina);
}
#Override
public String toString() {
return "Course: " + name + ", Disciplinas: {" + disciplinas.stream().collect(Collectors.joining(" ")) +"}";
}
}
Usage:
Course course = new Course("Computer Science", Arrays.asList("AlgProgII", "SO", "Grafos"));
System.out.println(course);
Output:
Course: Computer Science, Disciplinas: {AlgProgII SO Grafos}
Hi I am writing a code using polymorphism and I would like to print List on the screen but when I am using my code it run toString method from parent class only. How can I fix it?
public class HospitalApp {
public static void main(String[] main){
Hospital hospital = new Hospital();
List<Person> lista = new ArrayList<>();
lista = hospital.showList();
StringBuilder stringBuilder = new StringBuilder();
for(Person person : lista){
stringBuilder.append(person);
stringBuilder.append("\n");
}
System.out.println(stringBuilder.toString());
}
}
public class Hospital{
List<Person> lista = new ArrayList<>();
Person doktor = new Doctor("All", "Bundy",100, 99999);
Person nurse = new Nurse("Iga", "Lis",160, 10);
Person nurse_1 = new Nurse("Magda", "Andrych",160, 20);
public List showList(){
lista.add(doktor);
lista.add(nurse);
lista.add(nurse_1);
return lista;
}
}
public class Person{
private String imie;
private String nazwisko;
private double wyplata;
public Person(){}
public Person(String imie, String nazwisko, double wyplata){
this.imie = imie;
this.nazwisko = nazwisko;
this.wyplata = wyplata;
}
public void setImie(String imie){
this.imie = imie;
}
public String getImie(){
return imie;
}
public void setNazwisko(String nazwisko){
this.nazwisko = nazwisko;
}
public String getNazwisko(){
return nazwisko;
}
public void setWyplata(double wyplata){
this.wyplata = wyplata;
}
public double getWyplata(){
return wyplata;
}
public String toString(){
return getImie() + " " + getNazwisko() + " " + getWyplata();
}
}
public class Nurse extends Person{
private int nadgodziny;
public Nurse(){}
public Nurse(String imie, String nazwisko, double wyplata, int nadgodziny){
super(imie, nazwisko, wyplata);
this.nadgodziny = nadgodziny;
}
public void setNadgodziny(int nadgodziny){
this.nadgodziny = nadgodziny;
}
public int getNadgodziny(){
return nadgodziny;
}
#Override
String toString(){
return getImie() + " " + getNazwisko() + " " + getWyplata() + " " + getNadgodziny();
}
}
public class Doctor extends Person {
private double premia;
public Doctor(){}
public Doctor(String imie, String nazwisko, double wyplata , double premia){
super(imie, nazwisko, wyplata);
this.premia = premia;
}
public double getPremia(){
return premia;
}
public void setPremia(double premia){
this.premia = premia;
}
#Override
String toString(){
return getImie() + " " + getNazwisko() + " " + getWyplata() + " " + getPremia();
}
}
Can someone help me solve this problem?
The problem lies here, in the Person and Doctor class:
#Override
String toString(){
return ...;
}
you are missing the public specifier. There should be an error / warning about that. Apply it to the method signatures and your code will work as you expect it to.
probably you should add to the List not a Person (object) but a value returned by its toString method:
for(Person person : lista){
stringBuilder.append(person.toString);
stringBuilder.append("\n");
}
I have merged the above list but need to sort it based on the id param. How do I do that in the easiest and the optimal way possible?
I have a set of 2 users which I initially merged and now I would like to sort them based on their id and then display the results. Any ideas?
import java.io.*;
import java.util.*;
/*
* To execute Java, please define "static void main" on a class
* named Solution.
*
* If you need more classes, simply define them inline.
*/
class Employee {
public String name;
public int id;
Employee(String name, int id) {
this.name = name;
this.id = id;
}
public String toString() {
return "<name: " + this.name + ", id: " + this.id + ">";
}
}
class Person {
public String name;
public int id;
Person(String name, int id) {
this.name = name;
this.id = id;
}
public String toString() {
return "<name: " + this.name + ", id: " + this.id + ">";
}
}
public class Solution {
public static void main(String[] args) {
List<Employee> employee = generateEmployees();
List<Person> persons = generatePersons();
ArrayList<Object> merged = new ArrayList<Object>(employee);
merged.addAll(person);
System.out.println("merged:"+merged +"\n");
for(int i=0;i<users.size();i++){
if(person.get(i).id<=5){
System.out.println("UserName:"+person.get(i).name+"\n");
}
}
for(int i=0;i<employee.size();i++){
if(employee.get(i).id<=5){
System.out.println("DesignerName:"+employee.get(i).name+"\n");
}
}
});
}
Thanks in advance!
I have looked at several methods online for sorting but couldnt figureo ut which was the best way to use it.Just want to display results once its sorted
User and Designer must extend from one same class. (or Designer extand user).
Then you create a Comparator (javadoc) and you use merged.sort (myComparator) (javadoc)
[EDIT]
class MyComparator implements Comparator<User> {
#Override
public int compare(User o1, User o2) {
return Integer.compare(o1.id, o2.id);
}
}
public class User {
public String name;
public int id;
User(String name, int id) {
this.name = name;
this.id = id;
}
public String toString() {
return "<name: " + this.name + ", id: " + this.id + ">";
}
}
public class Designer extends User{
Designer(String enter code herename, int id) {
super(name, id);
}
}
public class Solution {
public static void main(String[] args) {
...
ArrayList<User> merged = new ArrayList<User>(designers);
merged.addAll(users);
merged.sort(new MyComparator());
...
}
}
Assuming that you have list of User that is called users:
users.stream().sorted(Comparator.comparing(User::getId)).forEach(System.out::println);
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 7 years ago.
I have a class , it passes objects,primitive . can anyone please explain this
public class TestObj {
String name;
int age;
public TestObj(String name, int age) {
this.name = name;
this.age = age;
}
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;
}
#Override
public String toString() {
return "TestObj{" + "name=" + name + ", age=" + age + '}';
}
}
main class
public class Test {
public static void main(String[] args) {
Test t = new Test();
TestObj obj = new TestObj("James", 25);
System.out.println("************* Output ****************");
System.out.println(obj);
t.setName(obj);
t.setAge(obj);
System.out.println(obj);
String a = "Hai Test";
System.out.println(">> :: " + a);
t.setString(a);
System.out.println(":: " + a);
int x = 10;
System.out.println("------- " + x);
t.setInt(x);
System.out.println("------- " + x);
}
public void setInt(int y) {
y = 25;
}
public void setString(String x) {
x = "Did i changed my Data";
}
public void setName(TestObj obj1) {
obj1.setName("I got Changed");
}
public void setAge(TestObj obj1) {
obj1.setAge(35);
}
}
************* Output ****************
TestObj{name=James, age=25}
TestObj{name=I got Changed, age=35}
:: Hai Test
:: Hai Test
------- 10
------- 10
java is 'pass-by-value'. always. but when a parameter is an object, the value is a reference (an address of an object), not the object itself