Save custom array of objects to file and read again in java? - java

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

Related

If I create an array of the parental class, how do I access a method from the sub class through the array object?

I have a program I am working with to help me practice my coding skills. The program has the following scenario: there is a classroom of 20 students, where the record is taken of the students' names, surnames, and age. Half of these students take part in the school's athletics. Here, record is kept of their races that they have done and the ones they've won.
In this program, I have three classes:
runStudents - class with main method
Students (String name, String surname, int age) - parental class
AthleticStudents (String name, String surname, int age, int races, int victories) - sub class
The user should be able to add another race (and win) to the object. As seen by the code provided, an Array is created to store the 20 Students objects. I have to be able to access a method to alter the object in the array, but this method is not in the parental class (the class the objects are created from.
public class Students
{
private String name;
private String surname;
private int age;
public Students()
{
}
public Students(String name, String surname, int age)
{
this.name = name;
this.surname = surname;
this.age = age;
}
public String getName()
{
return this.name;
}
public String getSurname()
{
return this.surname;
}
public double getAge()
{
return this.age;
}
public void setName(String name)
{
this.name = name;
}
public void setSurname(String surname)
{
this.surname = surname;
}
public void setAge(int age)
{
this.age = age;
}
public String toString()
{
return String.format("name\t\t: %s\nsurname\t\t: %s\nage\t\t: %s",
this.name, this.surname, this.age);
}
}
public class AthleticStudents extends Students
{
private int races;
private int victories;
public AthleticStudents()
{
}
public AthleticStudents(String name, String surname, int age, int
races, int victories)
{
super(name, surname, age);
this.races = races;
this.victories = victories;
}
public int getRaces()
{
return this.races;
}
public int getVictories()
{
return this.victories;
}
public void setRaces(int races)
{
this.races = races;
}
public void setVictories(int victories)
{
this.victories = victories;
}
public void anotherRace()
{
this.races = this.races + 1;
}
public void anotherWin()
{
this.victories = this.victories + 1;
}
public String toString()
{
return super.toString() + String.format("\nnumber of races\t:
%s\nnumber of wins\t: %s", this.races, this.victories);
}
}
public class runStudents
{
public static void main(String[]args)
{
Students[] myStudents = new Students[20];
myStudents[0] = new Students("John", "Richards", 15);
myStudents[1] = new AthleticStudents("Eva", "Grey", 14, 3, 1);
myStudents[2] = new Students("Lena", "Brie", 15);
for (int i = 0; i < 3; i++)
System.out.println(myStudents[i].toString() + "\n\n");
}
}
I want to be able to do the following:
AthleticStudents[1].anotherRace();
but cannot do so as the array object is derived from the parental class, and I declared the method in the sub class. How can I link the two?
I assume that you create an array of the parent class instances. Just cast the instance this way (you better check whether the element is the instance of a subclass):
if (AthleticStudents[1] instanceof AthleticStudents)
((AthleticStudents) AthleticStudents[1]).anotherRace();
I'm not sure if this is exactly what you're looking for but it worked well for me. Instead of trying to access AthleticStudents method anotherRace() like that, try this in your main method.
Students[] myStudents = new Students[20];
myStudents[0] = new Students("John", "Richards", 15);
myStudents[1] = new AthleticStudents("Eva", "Grey", 14, 3, 1);
myStudents[2] = new Students("Lena", "Brie", 15);
AthleticStudents addRace= (AthleticStudents)myStudents[1];
addRace.anotherRace(); //This will increment Eva's race count to 4
for (int i = 0; i < 3; i++)
System.out.println(myStudents[i].toString() + "\n\n");
All I did was cast the element into an object AthleticStudents named 'addRace'. By casting myStudents[1] to this new object you are able to access all of AthleticStudents methods.
I just saw the other answer posted which works just as well!
Hope this helps!
I’m not sure that i understand your question, because you are a bit inconsistent with your capitalization. runStudents is a class, while AthleticStudents is both a class and an array. But i’ll try.
IF i did understand your question, you have an array Student[] studentArray. Some Student objects in studentArray are AthleticStudents, others are not. You have a specific AthleticStudent eva which is in studentArray[] having let’s say index 1, and you want to add to her anotherRace(). Your call studentArray[1].anotherRace does not compile because the compiler treats that element as a Student and not as a AthleticStudent.
The trick is to cast the element to AthleticStudent. I omit the test of the element of being really an AthleticStudent; you will have to do that test in your code.
((AthleticStudent) studentArray[1]).anotherRace();

Generic linked list inside of linked list?

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

How do you fill an array with objects from a different class? deteils below

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

List iteration & setting values with Java 8 Streams API

I'm trying to understand how to use the Java 8 Streams API.
For example, I have these two classes:
public class User {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
public class UserWithAge {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
private int age;
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
}
I have a List<User> of ten users, and I want to convert this to a List<UserWithAge> of ten users with the same names and with a constant age (say, 27). How can I do that using the Java 8 Streams API (without loops, and without modifying the above classes)?
You could use the map() feature of the stream to convert each User instance in your list to a UserWithAge instance.
List<User> userList = ... // your list
List<UserWithAge> usersWithAgeList = userList.stream()
.map(user -> {
// create UserWithAge instance and copy user name
UserWithAge userWithAge = new UserWithAge();
userWithAge.setName(user.getName());
userWithAge.setAge(27);
return userWithAge;
})
.collect(Collectors.toList()); // return the UserWithAge's as a list
While you could do this, You should not do like this.
List<UserWithAge> userWithAgeList = new ArrayList<UserWithAge>();
userList.stream().forEach(user -> {
UserWithAge userWithAge = new UserWithAge();
userWithAge.setName(user.getName());
userWithAge.setAge(27);
userWithAgeList.add(userWithAge);
});
public class ListIteratorExp {
public static void main(String[] args) {
List<Person> list = new ArrayList<>();
Person p1 = new Person();
p1.setName("foo");
Person p2 = new Person();
p2.setName("bee");
list.add(p1);
list.add(p2);
list.stream().forEach(p -> {
String name = p.getName();
System.out.println(name);
});
}
}
class Person{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
output:-
vishal
thakur

Java Class Object having string array property initialization

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.

Categories