Storing User-Defined Classes in Collections (with Example)
In Java, you can store objects of user-defined classes in collections like ArrayList
, HashSet
, TreeSet
, etc. To do this effectively, especially for searching, sorting, or uniqueness, the class should override toString()
, equals()
, and hashCode()
(for Hash-based collections) or implement Comparable
(for sorted collections).
Example: Storing Student Objects in an ArrayList
1. User-Defined Class: Student
class Student { int id; String name; Student(int id, String name) { this.id = id; this.name = name; } // Override toString() for readable output @Override public String toString() { return "ID: " + id + ", Name: " + name; } }
2. Main Program Using ArrayList<Student>
import java.util.ArrayList; public class UserDefinedCollectionExample { public static void main(String[] args) { // Create a list to store Student objects ArrayList<Student> students = new ArrayList<>(); // Add student objects students.add(new Student(101, "Alice")); students.add(new Student(102, "Bob")); students.add(new Student(103, "Charlie")); // Display the list System.out.println("Student List:"); for (Student s : students) { System.out.println(s); } } }
Output:
Student List: ID: 101, Name: Alice ID: 102, Name: Bob ID: 103, Name: Charlie
Notes:
- If you use a
HashSet
orHashMap
, overrideequals()
andhashCode()
. - If you use a
TreeSet
or want to sort the list, implementComparable
or use aComparator
.