I have a POJO class with one of String array property having size is 2. But I am creating the object of Person class with passing array of size 5. It's not showing any exception. Why?
package classObject;
import java.util.Arrays;
public class Person implements Cloneable {
String name;
int age;
String[] skills = new String[2];
Person() {
}
Person(String name, int age, String[] skills) {
this.name = name;
this.age = age;
System.out.println("this.skills.length " + this.skills.length);
System.out.println("skills.length " + skills.length);
this.skills = skills;
System.out.println("Got array is " + Arrays.asList(this.skills));
System.out.println("length of arrays is " + this.skills.length);
}
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
protected Person clone() throws CloneNotSupportedException {
return (Person) super.clone();
}
public String[] getSkills() {
return skills;
}
public void setSkills(String[] skills) {
this.skills = skills;
}
}
// Creating the Object of Person Class
public class classObject {
/* Way to create an object of any class */
public static void main(String args[]) {
try {
// Define the array with len 5
String[] skills = new String[5];
skills[0] = "Java";
skills[1] = "PHP";
skills[2] = "JDBC";
skills[3] = "ORACLE";
skills[4] = "SQL";
// Passing the array
Person objPerson = new Person("Mohit", 27, skills);
System.out.println("Size is " + objPerson.skills.length);
} catch (Exception e) {
e.printStackTrace();
}
}
}
String[] is an object, although it doesn't look like it. So when you declare.
String[] skills = new String[2];
You're actually declaring a pointer to a new object, which is a String[] object, with a size of 2.
Then you come a long with a new String[] object of size 5, and your reference now points to that.
This process has nothing to do with the original object, because when you state:
this.skills = skills;
you're not effecting the object that this.skills points to; only the pointer itself. The String[2] object will have no pointers referring to it, and the garbage collector will likely come a long and destroy it.
You're pointing the class variable to the argument passed in the function... Check its' size in the constructor and if it's not 2, then throw IllegalArgumentExepction.
Related
I am trying to use BiConsumer to accept an object that contains variables, an object and a list of strings in Java. I am not sure how to set the values into one object if using just BiConsumer. Maybe, if I tried to wrap Student object in a List and pass it into a new Student might help, but so far I get a null object. I haven't seen a lot of post with object containing just variables in one object and using BiConsumer.
#Test
public void testStudent() {
List<Object> objectList1 = new ArrayList<>();
Student student = new Student();
StudentLevel studentLevel = new StudentLevel("freshman", true);
List<String> studentLists = Arrays.asList("Maria", "Jose", "Juan");
Student student1 = new Student("Maria", "Lopez", "A", studentLevel, studentLists);
objectList1.add(student1);
BiConsumer<Object, List<Object>> biconsumer = (obj, list) -> {
for (Object object: list) {
// set and get but how?
// obj = object;
}
};
// To accept values from the object list see below for desired output
biconsumer.accept(student, objectList1);
// For debugging purpose
System.out.println("All Student: " + student);
}
public class Student {
private String name;
private String lastName;
private String grade;
private StudentLevel studentGrade;
private List<String> studentList;
public Student(final String name, final String lastName, final String grade, final StudentLevel studentGrade, final List<String> studentList) {
this.name = name;
this.lastName = lastName;
this.grade = grade;
this.studentGrade = studentGrade;
this.studentList = studentList;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public StudentLevel getStudentGrade() {
return studentGrade;
}
public void setStudentGrade(StudentLevel studentGrade) {
this.studentGrade = studentGrade;
}
public List<String> getStudentList() {
return studentList;
}
public void setStudentList(List<String> studentList) {
this.studentList = studentList;
}
}
public class StudentLevel {
private String level;
private Boolean pass;
public StudentLevel(final String level, final Boolean pass){
this.level = level;
this.pass = pass;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public Boolean getPass() {
return pass;
}
public void setPass(Boolean pass) {
this.pass = pass;
}
}
Desired output:
student = {Student#887}
name = "Maria"
lastName = "Lopez"
grade = "A"
studentGrade = {StudentLevel#889}
level = "freshman"
pass = {Boolean#906} true
studentList = {Arrays$ArrayList#890} size = 3
0 = "Maria"
1 = "Jose"
2 = "Juan"
You are assigning local reference of object to obj (won't copy the values)
obj = object; // means, student = object
no change will be reflected outside the scope of the consumer, instead, you need to modify the state using setters as:
((Student) obj).setName(((Student) object).getName());
obj = object; // after this point, student object won't be accessible in the current scope.
Note: You should have getters and setters to access private properties outside Student class, and this example just demonstrates the working by assigning name property.
Reference:
• Classes and Object
I am trying to write a program which stores information about a person in a linked list. I made a simple person class to store the name, age and addresses in the list. I would also like to store multiple addresses for EACH person, and a fact about the place in another linked list, inside the person class.
So for example, "Tara" can have a home address of "10 Central Ave" and a work address of "5 Willow street" etc. The problem is, I don't know how to have a linked list inside another.
My goal is to check whether the person's name is already on the list, and if so, add another address for them. (So that there is no repeats). I am a beginner and can really use some help.
public class Person {
private String name;
private int age;
public LinkedList <String> adresses;
public Person() {
name = "default";
age = 0;
adresses = new LinkedList<>();
}
public Person(String n, int a) {
name = n;
age = a;
}
public LinkedList<Adress> getAdresses() {
return adresses;
}
public void setAdresses(LinkedList<Adress> adresses) {
this.adresses = adresses;
}
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 String toString() {
return name+" "+age+" "+adresses;
}
}
public class Adress {
public String adress;
public String fact;
public Adress(String a, String f) {
adress = a;
fact = f;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public String getFact() {
return fact;
}
public void setFact(String fact) {
this.fact = fact;
}
}
public class Test {
public static void main(String[] args) {
Person Tara = new Person("Tara",35);
Person Judah = new Person("Judah",28);
Person Mark = new Person("Mark",45);
Person Seth = new Person("Seth",23);
LinkedList<Object> tester = new LinkedList<>();
tester.add(Tara);
tester.add(Judah);
tester.addLast(Mark);
tester.addLast(Seth);
System.out.println(tester);
}
}
How is about to use the next classic data structure for your project?
public class Person {
private String name
private int age;
public List<Address> addresses;
//...
}
"This question is for a free online course I am taking. Below is the instructors direction and below that is my answer. I must be solving the problem wrong because the automatic grading system marks it incorrect even though I got the correct output. I believe the instructor wanted me to fill an array in the Main class with objects from the person class and I am unsure how to do that. Please help if you know how to do that or if you have a better idea of what the instructor wanted."
Instructors direction
In your main method, make an array of type Person Fill it with Person objects of the following people and then print the names of each from that array. Each person should be on their own line formatted as shown below.
Fred, 24
Sally, 26
Billy, 15
main.java
class Main {
public static Person[] people;
public static void main(String[] args) {
Person personObject = new Person();
personObject.Person();
}
}
Person.java
public class Person{
public static String[] Person(){
String[] people = {"Fred, 24", "Sally, 26", "Billy, 15"};
for(int i=0; i< people.length; i++){
System.out.println(people[i]);
}
return people;
}
}
It says you need objects and array. So i guess you wanted something like this.
Person.java
public class Person {
private String name;
private int age;
public Person(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 "Person{" + "name=" + name + ", age=" + age + '}';
}
}
By declaring Person p1 = new Person("Sally",26); you are creating object of class Person. You can use that as many times as you want and create different objects. We use override method toString to print informations about Person. We could also use p1.getName() and p1.getAge()
Main
public static void main(String[] args) {
Person p1 = new Person("Fred", 24);
Person p2 = new Person("Sally", 26);
Person p3 = new Person("Billy", 55);
Person[] people = {p1,p2,p3};
for(Person p : people){
System.out.println(p.toString());
}
}
I think what your professor wants is something like this :)
public class Runner {
public static void main(String args[])throws Exception{
Persons person1 = new Persons();
Persons person2 = new Persons();
Persons person3 = new Persons();
person1.setName("Fred");
person1.setAge("24");
person2.setName("Sally");
person2.setAge("26");
person3.setName("Billy");
person3.setAge("15");
String[] list = {person1.toString(), person2.toString(), person3.toString()};
for (int i = 0; i < list.length; i++) {
System.out.println(list[i]);
}
}
}
public class Persons {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
#Override
public String toString() {
return name + ", " + age;
}
}
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.
}
}
I would like to save an array of objects that is custom as a file and re-read it back as an array of objects on program start in java. If I could also save it as JSON, it would be nice. I have tried some common methods but I get a error saying that my array is not serialiazable.
class ArrayOfObjects {
public static void main (String[] args) throws Exception {
Students[] studentArray = new Students[3];
studentArray[0] = new Students();
studentArray[0].age = 18;
studentArray[0].name = "Jones";
studentArray[1] = new Students();
studentArray[1].age = 21;
studentArray[1].name = "David";
studentArray[2] = new Students();
studentArray[2].age = 15;
studentArray[2].name = "Jeremy";
}
}
class Students {
int age;
String name;
}
your class Students should implement Serialiazble
If you want to save it in standard output, Students must implement Serializable.
If you wan to save it as JSON, use Jackson (http://fasterxml.com/) and normalise it Java bean declaration to the class.
class Students implemenst Serializable {
private int age;
private String 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;
}
}