user15154296
user15154296

Reputation:

Get info of an object in a ArrayList

I've created an ArrayList where I put some objects. When I create an object, I can retrieve some info by doing :

objectX.getActivityName();

My problem is when I put all my objects in my ArrayList, I can't access to my getActivityName Example :

for (Object temp:tabRegristre) {
        System.out.println("TEMPS : " + temp); // I want to show the temp object Activity Name not all the info of the object.

    }

Is there any solution to show only some info of my object from the for each loop? Instead of printing the object itself?

Thanks!!

Upvotes: 0

Views: 107

Answers (1)

Basil Bourque
Basil Bourque

Reputation: 338211

Generics

You need to learn about Java Generics and using angle brackets < & >. See tutorial by Oracle.

For a brief class definition, use the new records feature in Java 16. (Or use a conventional class.)

public record Activity ( String name , LocalDate when ) {}

Make a couple of those objects.

Activity brunch = new Activity( "Brunch" , LocalDate.of( 2021 , Month.MARCH , 15 ) ) ;
Activity meeting = new Activity( "Meeting" , LocalDate.of( 2021 , Month.APRIL , 23 ) ) ;

Define your collection. Notice how we use the angle brackets to tell the compiler that we want to restrict this list to containing only objects of type Activity.

List< Activity > activities = new ArrayList< Activity >() ;

The compiler can infer the class Activity on the right side of assignment =. So no need to repeat.

List< Activity > activities = new ArrayList<>() ;

Add your objects to the collection.

activities.add( brunch ) ;
activities.add( meeting ) ;

Retrieve each object. Print date. The accessor method carries the same name as its property. So when() is the accessor method for our LocalDate property named when.

The compiler knows that only Activity objects went into the collection, so retrieved items must be Activity objects. No need for casting (explicit type conversion).

for( Activity activity : activities ) 
{
    System.out.println( activity.when() ) ;
}

Upvotes: 3

Related Questions