How to choose using Collection<Id> rather than Collection<String>, or the opposite?

Both String and Id are primitive data types in apex. Consider below scenario:

public class poc {
    static List<Id> ids = new List<Id>();
    public static void check() {
        try {
            ids.add('invalid_id');
            System.debug('ids => '+ids);
        }
        catch(Exception ex) {
            System.debug('ERROR => '+ex.getMessage());
        }
    }   
}

Here when you invoke check(), it will throw error saying Invalid id: invalid_id as 'invalid_id' is actually not a valid salesforce Id.

However when you define List<String> variable and add Id to that variable, apex internally converts Id datatype to String and adds it.

IMPORTANT:

  1. When you expect a collection to have Ids, then always define use type Id only so that you do not add string inadvertantly. This is a best practice.

  2. When you dont know which data type it may contain, you can use String and later convert String to Id using Id.valueOf(String). But before converting, it is best practice to check if its valid Id using instanceof. Example below:

    System.debug('aa' instanceof Id); //false
    System.debug('0010K00001fr5LhQAI' instanceof Id); //true
    

Ids are a subset of Strings. The advantage of using Id is that it has its own methods that you could use from here:

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_id.htm

But in a lot of cases I'd say it's not that big of a deal if you use string instead of Id. I try to use Id if I know for sure it is an Id. I think it makes the code cleaner