11.12. Understanding bit more of it

Understanding a bit more of it

  • Eclipse: Oxygen
  • Java: 1.8

This article generalizes all the tutorials studied so far in the Collections framework. If we define the type of List as an Object, we can add all kinds of Objects, such as Integers, the String, and even some characters. Therefore, all the defined techniques can work, except for sort which only works for elements with the same datatype.

In the following example, we replace the type of List from names to Object, which makes it more generic and allows the user to use any type of data without any restriction (Object is the parent class of all the classes).

Folder Structure

Explanation

The program starts by defining a class called Names, which encapsulates a single private instance variable name of type String. The Names class also includes a constructor that takes a String parameter and assigns it to the name variable. Additionally, the class overrides the toString() method to provide a customized string representation of a Names object.

Within the App class, the main method serves as the entry point of the program. It creates a LinkedList named elements with a generic type of Object. The elements list is then populated with various elements, including instances of the Names class, a string, an integer, a double, and a character.

An instance of the App class is created, and the printList method is invoked, passing the elements list as an argument. The printList method takes a List of Objects as a parameter, and it iterates over the elements using a ListIterator. During each iteration, the current element is printed to the console with the prefix “Element: “.

Output

Output Explanation

The program iterates over the elements list using the listIterator and prints each element to the console with the “Element: ” prefix. Since the elements list contains a mixture of different object types, including Names objects, a string, an integer, a double, and a character, the output will display the string representation of each object.

This output reflects the contents of the elements list and demonstrates the polymorphic behavior of the List, accommodating different types of objects in a single collection.

Contributed by: Salim Sheikh

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback
3 years ago

Google

Very couple of web sites that transpire to become in depth below, from our point of view are undoubtedly very well worth checking out.