Arrays and objects are two fundamental data structures in Java that perform various functions. Objects are collections of connected data and behavior whereas arrays are collections of comparable data types.
When working with complex data structures or passing data across various portions of your program sometimes you may need to transform an array to an object. This conversion includes converting the array’s elements into object fields.
Why do we need to convert array to object in java
Some possible reasons why you may need to convert an array to an object in Java are:
- Enhanced functionality: Arrays have functional constraints, whereas objects can include methods and fields that give increased functionality.
- Encapsulation: Objects allow you to encapsulate related data and behavior into a single unit, making your code more modular and understandable.
- Passing data between methods: Supplying an array as a parameter to a method implies passing a reference to the array.
- Interoperability: Converting an array to an object may make serializing and transferring data between systems or languages easier.
How to convert array to object in java
Some possible approaches to convert an array to an object in Java are:
- Using a constructor
- Using setters
- Using reflection
- Using streams
- Using the Arrays class
Approaches
Approach 1: Using a constructor
To convert an array to an object, we first create an object and attempt to send the array as an input to the constructor. The constructor may then be used to initialise the array elements in the object’s fields.
class Person {
private String name;
private int age;
private String[] hobbies;
public Person(String name, int age, String[] hobbies) {
this.name = name;
this.age = age;
this.hobbies = hobbies;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String[] getHobbies() {
return hobbies;
}
}
public class Main {
public static void main(String[] args) {
String[] hobbies = {"reading", "traveling", "hiking"};
Person person = new Person("John Doe", 30, hobbies);
System.out.println(person.getName());
System.out.println(person.getAge());
System.out.println(Arrays.toString(person.getHobbies()));
}
}
Output:
John Doe
30
[reading, traveling, hiking]
Explanation:
- In the main() method, we create an array of String objects called hobbies and initialize it with some values.
- We then create a new Person object called person and pass the name, age, and hobbies array to the constructor.
- We use getter methods to get the name, age and hobbies of the person object and print them to the console.
Approach 2: Using setters
In Java, using setters to transform an array to an object entails looping through the array and invoking the correct setter method for each element.
Sample Code:
class Person {
private String name;
private int age;
private String[] hobbies;
// setters
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setHobbies(String[] hobbies) {
this.hobbies = hobbies;
}
// getters
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String[] getHobbies() {
return hobbies;
}
}
class Main {
public static void main(String[] args) {
// set the name, age, and hobbies of the person object using setter methods
String[] hobbies = {"Going to Office", "Being Funny", "Wassupp!!"};
Person person = new Person();
person.setName("Michael Scott");
person.setAge(48);
person.setHobbies(hobbies);
System.out.println(person.getName());
System.out.println(person.getAge());
System.out.println(Arrays.toString(person.getHobbies()));
}
}
Output:
Michael Scott
48
[Going to Office, Being Funny, Wassupp]
Explanation:
- We create a Person class with three fields: name of type String, age of type int, and hobbies of type String[].
- We define setter methods for each of these fields that set their values.
- In the main() method, we create an array of String objects called hobbies and initialize it with some values.
- We then create a new Person object called as person. We call the objects as setName(), setAge(), and setHobbies() methods that function as set the name, age and hobbies fields respectively.
- We use getter methods to retrieve the person object’s name, age, and hobbies and output them to the console.
Approach 3: Using reflection
Reflection is used in Java to transform an array to an object by dynamically checking the object’s class and fields at runtime and changing their values using the array elements.
import java.lang.reflect.*;
class Person {
import java.lang.reflect.*;
class Person {
private String name;
private int age;
private String[] hobbies;
// default constructor
public Person() {
}
public Person(String name, int age, String[] hobbies) {
this.name = name;
this.age = age;
this.hobbies = hobbies;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String[] getHobbies() {
return hobbies;
}
}
class Main {
public static void main(String[] args) throws Exception {
String[] hobbies = {"Chemist", "Teacher"};
// Get the class object for Person
Class<?> personClass = Class.forName("Person");
// Get the default constructor for Person
Constructor<?> constructor = personClass.getConstructor();
// Create a new instance of Person using the default constructor
Person person = (Person) constructor.newInstance();
// Get the setName(), setAge(), and setHobbies() methods for Person
Method setNameMethod = personClass.getDeclaredMethod("setName", String.class);
Method setAgeMethod = personClass.getDeclaredMethod("setAge", int.class);
Method setHobbiesMethod = personClass.getDeclaredMethod("setHobbies", String[].class);
// Use the methods to set the values for the fields of Person
setNameMethod.invoke(person, "Walter White");
setAgeMethod.invoke(person, 53);
setHobbiesMethod.invoke(person, (Object) hobbies);
// Print out the values of the fields of Person
System.out.println(person.getName());
System.out.println(person.getAge());
System.out.println(person.getHobbies());
}
}
Output:
Walter White
53
[Chemist, Teacher]
Explanation:
- In the main() method, we create an array of String objects called hobbies and initialize it with some values.
- We then create a new Person object called as person. We call the objects as setName(), setAge(), and setHobbies() methods that function as set the name, age and hobbies fields respectively.
- We use getter methods to retrieve the person object’s name, age, and hobbies and output them to the console.
Approach 4: Using streams
For converting an array to an object we need to first construct a stream of the array elements and then use the map() method to transform each element into an object.
import java.util.Arrays;
class Person {
private String name;
private int age;
private String[] hobbies;
public Person(String name, int age, String[] hobbies) {
this.name = name;
this.age = age;
this.hobbies = hobbies;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String[] getHobbies() {
return hobbies;
}
}
class Main {
public static void main(String[] args) {
String[] hobbies = {"Fly", "Help", "Go to gym"};
// Create a Person object using the array of values and the constructor reference
Person person = Arrays.stream(new Object[][]{{"Superman", 24, hobbies}})
.map(arr -> new Person((String)arr[0], (int)arr[1], (String[])arr[2]))
.findFirst()
.orElse(null);
// Print out the values of the fields of Person
System.out.println(person.getName());
System.out.println(person.getAge());
System.out.println(Arrays.toString(person.getHobbies()));
}
}
Output:
Superman
24
[Fly, Help, Go to gym]
Explanation:
- We define a parameterized constructor that takes three arguments to set the values of the fields.
- In the main() method, we create an array of String objects called hobbies and initialize it with some values.
- We create a Person object using the array of values and the constructor reference using the Arrays.stream() method.
- We use the map() method to map the array of objects to a Person object using the constructor and cast the values to the correct data types.
- We utilise the findFirst() function to fetch and return the first Person object from the stream.
- We use getter methods to get the name, age, and interests of the person object and print them to the console.
Approach 5: Using the Arrays class
For converting an array to an object in Java we need to first convert the array to a List object, then construct a new object and supply the List object as an input to the constructor.
import java.util.Arrays;
class Person {
private String name;
private int age;
private String[] hobbies;
public Person(String name, int age, String[] hobbies) {
this.name = name;
this.age = age;
this.hobbies = hobbies;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String[] getHobbies() {
return hobbies;
}
}
class Main {
public static void main(String[] args) {
String[] hobbies = {"Astrophysicist", "Being with Howard", "Cinnamon"};
// Use the Arrays class to create a Person object from the array of values
Person person = new Person("Rajesh Ramayan Kootrapali", 29, hobbies);
// Print out the values of the fields of Person
System.out.println(person.getName());
System.out.println(person.getAge());
System.out.println(Arrays.toString(person.getHobbies()));
}
}
Output:
Rajesh Ramayan Kootrapali
29
[Astrophysicist, Being with Howard, Cinnamon]
Explanation:
- We define a parameterized constructor that takes three arguments to set the values of the fields.
- In the main() method, we create an array of String objects called hobbies and initialize it with some values.
- We create a Person object using the array of values and the constructor.
- We use getter methods to retrieve the person object’s name, age, and hobbies and output them to the console.
Best Approach
Using a constructor to transform an array to an object is regarded as one of the finest Java ways because:
- It ensures that all necessary fields are initialized when the object is created, preventing errors or unexpected behavior later on.
- It follows the encapsulation idea, which is a key feature of object-oriented programming.
- It provides a clear and easy approach for constructing objects with a preset set of initial values.
- Constructors can accept numerous parameters and be overloaded, making it possible to create objects with varying initial values.
- It is a generally acknowledged and extensively used strategy in Java that makes the code easier for other developers to comprehend and maintain.
Sample Question
Sample Problem 1:
Write a program using a constructor method to create a Book class with fields title, author, year, and price. Create a constructor that accepts an array of values. It sets the fields to their default values. The program should create an array of book data and use the constructor to create an array of Book objects, and then print out the values of each object’s fields.
Solution:
- The Book class will include private fields for title, author, year and price.
- We will need to as well as create a constructor that accepts an array of values and initializes the fields.
- The main method creates an array of book data and an array of Book objects using the constructor, and then prints out the values of each object’s fields.
- The Integer.parseInt and Double.parseDouble methods are used to convert the year and price fields from strings to integers and doubles, respectively.
- The getTitle, getAuthor, getYear, and getPrice methods are used to access the private fields from outside the class.
class Book {
private String title;
private String author;
private int year;
private double price;
// Constructor that takes an array of values and initializes the fields
public Book(String[] data) {
this.title = data[0];
this.author = data[1];
this.year = Integer.parseInt(data[2]);
this.price = Double.parseDouble(data[3]);
}
// Getters for the fields
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public int getYear() {
return year;
}
public double getPrice() {
return price;
}
public static void main(String[] args) {
// Create an array of book data
String[][] bookData = {
{"To Kill a Mockingbird", "Harper Lee", "1960", "9.99"},
{"The Great Gatsby", "F. Scott Fitzgerald", "1925", "12.50"},
{"1984", "George Orwell", "1949", "8.99"},
{"Pride and Prejudice", "Jane Austen", "1813", "5.99"},
{"Animal Farm", "George Orwell", "1945", "7.99"}
};
// Create an array of Book objects using the constructor
Book[] books = new Book[bookData.length];
for (int i = 0; i < bookData.length; i++) {
books[i] = new Book(bookData[i]);
}
// Print out the values of each object's fields
for (Book book : books) {
System.out.println(book.getTitle() + " by " + book.getAuthor() +
", published in " + book.getYear() + ", costs " + book.getPrice());
}
}
}
Output:
To Kill a Mockingbird by Harper Lee, published in 1960, costs 9.99
The Great Gatsby by F. Scott Fitzgerald, published in 1925, costs 12.5
1984 by George Orwell, published in 1949, costs 8.99
Pride and Prejudice by Jane Austen, published in 1813, costs 5.99
Animal Farm by George Orwell, published in 1945, costs 7.99
Sample Problem 2:
Write a program using a setters method to create a Car class with fields make, model, year, and color. Create setter methods for each field. The programme should generate an array of car data, use setters to initialize the fields of a Car object for each item in the array, and then output the values of each object’s fields.
Solution:
- The Car class is defined with private fields make, model, year, and color, and corresponding setter and getter methods.
- A main method is developed to generate an array of automobile data, which is a 2D array of strings including each car’s manufacturer, model, year, and colour.
- An array of Car objects is created, with each object initialized using the setter methods to set the fields to the values in the corresponding row of the car data array.
- The values of each object’s fields are printed out using the getter methods.
class Car {
private String make;
private String model;
private int year;
private String color;
// Constructor
public Car() {
// Default constructor
}
// Setters
public void setMake(String make) {
this.make = make;
}
public void setModel(String model) {
this.model = model;
}
public void setYear(int year) {
this.year = year;
}
public void setColor(String color) {
this.color = color;
}
// Getters
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public int getYear() {
return year;
}
public String getColor() {
return color;
}
public static void main(String[] args) {
String[][] carData = {
{"Toyota", "Camry", "2021", "Silver"},
{"Honda", "Accord", "2019", "Red"},
{"Ford", "F-150", "2018", "Black"}
};
Car[] cars = new Car[3];
// Create Car objects and initialize fields using setter methods
for (int i = 0; i < carData.length; i++) {
Car car = new Car();
car.setMake(carData[i][0]);
car.setModel(carData[i][1]);
car.setYear(Integer.parseInt(carData[i][2]));
car.setColor(carData[i][3]);
cars[i] = car;
}
// Print out the values of each object's fields
for (int i = 0; i < cars.length; i++) {
System.out.println("Car #" + (i + 1));
System.out.println("Make: " + cars[i].getMake());
System.out.println("Model: " + cars[i].getModel());
System.out.println("Year: " + cars[i].getYear());
System.out.println("Color: " + cars[i].getColor());
System.out.println();
}
}
}
Output:
Car #1
Make: Toyota
Model: Camry
Year: 2021
Color: Silver
Car #2
Make: Honda
Model: Accord
Year: 2019
Color: Red
Car #3
Make: Ford
Model: F-150
Year: 2018
Color: Black
Sample Problem 3:
Write a program using a reflection method to create a Person class with fields name, age, and occupation. Create an array of values and use reflection to create a Person object and initialize its fields. The program should print out the values of each object’s fields.
Solution:
- To initialize the fields of the Person object, define an array of values.
- Create a new Person object using reflection by getting the class object for Person and calling the newInstance() method.
- Get the fields of the Person object using getDeclaredFields() method.
- Using the Field class’s set() method, loop through the fields and set their values. To grant access to private fields, use the setAccessible() function.
- Print out the field values of the Person object using its toString() method.
import java.lang.reflect.Field;
class ReflectionExample {
public static void main(String[] args) {
try {
// Define array of values
Object[] values = {"Alice", 25, "Engineer"};
// Create new Person object using reflection
Class<?> personClass = Class.forName("Person");
Object personObj = personClass.newInstance();
// Set field values using reflection
Field[] fields = personClass.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
field.setAccessible(true);
field.set(personObj, values[i]);
}
// Print out field values
System.out.println(personObj.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Person {
private String name;
private int age;
private String occupation;
public Person() {}
public Person(String name, int age, String occupation) {
this.name = name;
this.age = age;
this.occupation = occupation;
}
public String toString() {
return "Name: " + name + ", Age: " + age + ", Occupation: " + occupation;
}
}
Output:
Name: Alice, Age: 25, Occupation: Engineer
Sample Problem 4:
Write a program using a stream method to create a SportsTeam class with fields name, sport, city, and players. Create an array of team data and use streams to create an array of SportsTeam objects, with the players field initialized as a list of player names. The program should print out the values of each object’s fields.
Solution:
- Create an array of team data, with each element representing a SportsTeam object as an array of values.
- Use streams to map each element of the team data array to a SportsTeam object, using the constructor that takes the name, sport, city, and players list as arguments. The Arrays.asList() method is used to convert the array of player names to a list.
- Collect the SportsTeam objects into an array using the toArray() method.
- Print out the field values of each SportsTeam object using its toString() method.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
class SportsTeamExample {
public static void main(String[] args) {
// Define array of team data
Object[][] teamData = {
{"Team A", "Football", "New York", new String[]{"John", "Mike", "Tom"}},
{"Team B", "Basketball", "Los Angeles", new String[]{"James", "Kobe", "Shaquille"}},
{"Team C", "Hockey", "Toronto", new String[]{"Wayne", "Mario", "Sidney"}}
};
// Use streams to create array of SportsTeam objects
SportsTeam[] teams = Arrays.stream(teamData)
.map(data -> new SportsTeam((String) data[0], (String) data[1], (String) data[2],
Arrays.asList((String[]) data[3])))
.toArray(SportsTeam[]::new);
// Print out field values of each SportsTeam object
for (SportsTeam team : teams) {
System.out.println(team.toString());
}
}
}
class SportsTeam {
private String name;
private String sport;
private String city;
private List<String> players;
public SportsTeam(String name, String sport, String city, List<String> players) {
this.name = name;
this.sport = sport;
this.city = city;
this.players = players;
}
public String toString() {
return "Name: " + name + ", Sport: " + sport + ", City: " + city + ", Players: " + players.toString();
}
}
Output:
Name: Team A, Sport: Football, City: New York, Players: [John, Mike, Tom]
Name: Team B, Sport: Basketball, City: Los Angeles, Players: [James, Kobe, Shaquille]
Name: Team C, Sport: Hockey, City: Toronto, Players: [Wayne, Mario, Sidney]
Sample Problem 5:
Write a program using an array class method to create a Movie class with fields title, director, genre, and actors.Make an array of movie data, then use the Arrays class to create an array of Movie objects with an array of actor names in the actors field. The values of each object’s fields should be printed by the programme.
Solution:
- We define a Movie class with fields for the movie’s title, director, genre, and actors.
- We create a constructor that takes these fields as parameters.
- We create getter methods for each field.
- We also make an array of movie data with the actors field set to an array of actor names.
- We use the Arrays class to create an array of Movie objects from the movie data array using streams.
- We construct a new Movie object for each row of movie data, with the title, director, genre, and actors fields initialised from the data. Using the comma divider, we separated the actors text into an array.
- We convert the stream of Movie objects into an array using the toArray method.
- Finally, we loop through the array of Movie objects and print out the values of each object’s fields.
import java.util.Arrays;
class Movie {
private String title;
private String director;
private String genre;
private String[] actors;
public Movie(String title, String director, String genre, String[] actors) {
this.title = title;
this.director = director;
this.genre = genre;
this.actors = actors;
}
public String getTitle() {
return title;
}
public String getDirector() {
return director;
}
public String getGenre() {
return genre;
}
public String[] getActors() {
return actors;
}
public static void main(String[] args) {
String[][] movieData = {
{"The Dark Knight", "Christopher Nolan", "Action", "Christian Bale, Heath Ledger, Aaron Eckhart"},
{"Inception", "Christopher Nolan", "Science Fiction", "Leonardo DiCaprio, Ken Watanabe, Joseph Gordon-Levitt"},
{"The Shawshank Redemption", "Frank Darabont", "Drama", "Tim Robbins, Morgan Freeman, Bob Gunton"}
};
Movie[] movies = Arrays.stream(movieData)
.map(data -> new Movie(data[0], data[1], data[2], data[3].split(", ")))
.toArray(Movie[]::new);
for (Movie movie : movies) {
System.out.println("Title: " + movie.getTitle());
System.out.println("Director: " + movie.getDirector());
System.out.println("Genre: " + movie.getGenre());
System.out.println("Actors: " + Arrays.toString(movie.getActors()));
System.out.println();
}
}
}
Output:
Title: The Dark Knight
Director: Christopher Nolan
Genre: Action
Actors: [Christian Bale, Heath Ledger, Aaron Eckhart]
Title: Inception
Director: Christopher Nolan
Genre: Science Fiction
Actors: [Leonardo DiCaprio, Ken Watanabe, Joseph Gordon-Levitt]
Title: The Shawshank Redemption
Director: Frank Darabont
Genre: Drama
Actors: [Tim Robbins, Morgan Freeman, Bob Gunton]
Conclusion
Finally we can say that there are several techniques on how to convert arrays to objects in java including using a constructor, setters, reflection, streams or an Arrays class.
Each method has its advantages and disadvantages and the ideal method to utilize is determined by the unique use case and personal choice.
Consider readability, performance, and ease of use while selecting an approach. If you need to perform further operations, the constructor method is an excellent choice if you want a concise and clean solution.