import java.util.List;
public class ListValidator {
/**
* Validates a list for basic sanity checks.
*
* @param list The list to validate.
* @param <T> The type of elements in the list.
* @return True if the list is valid, false otherwise.
*/
public static <T> boolean validateList(List<T> list) {
if (list == null) {
System.err.println("List is null.");
return false;
}
if (list.isEmpty()) {
System.err.println("List is empty.");
return true; // Empty lists are considered valid by default
}
for (T element : list) {
if (element == null) {
System.err.println("List contains a null element.");
return false;
}
}
return true;
}
/**
* Validates if all elements in a list are of the same type.
* @param list The list to validate
* @param <T> The type of the list elements
* @return True if all elements are of the same type, false otherwise.
*/
public static <T> boolean validateSameType(List<T> list) {
if (list == null || list.isEmpty()) {
return true; // Consider null or empty lists as valid
}
T firstElement = list.get(0);
if (firstElement == null) {
System.err.println("List contains a null element.");
return false;
}
for (T element : list) {
if (element == null) {
System.err.println("List contains a null element.");
return false;
}
if (!firstElement.getClass().equals(element.getClass())) {
System.err.println("List contains elements of different types.");
return false;
}
}
return true;
}
/**
* Validates if the list contains only positive numbers.
* @param list The list to validate
* @param <T> The type of list elements (must be Number)
* @return True if all elements are positive numbers, false otherwise.
*/
public static <T extends Number> boolean validatePositiveNumbers(List<T> list) {
if (list == null) {
System.err.println("List is null.");
return false;
}
for (T element : list) {
if (element == null) {
System.err.println("List contains a null element.");
return false;
}
if (element.doubleValue() <= 0) {
System.err.println("List contains non-positive numbers.");
return false;
}
}
return true;
}
public static void main(String[] args) {
// Example usage
List<String> stringList = List.of("apple", "banana", "cherry");
System.out.println("String list is valid: " + validateList(stringList));
List<Integer> intList = List.of(1, 2, 3, 4, 5);
System.out.println("Integer list is valid: " + validateList(intList));
List<Object> mixedList = List.of(1, "hello", 3.14);
System.out.println("Mixed list is valid: " + validateList(mixedList));
List<String> nullList = null;
System.out.println("Null list is valid: " + validateList(nullList));
List<String> emptyList = List.of();
System.out.println("Empty list is valid: " + validateList(emptyList));
List<Integer> sameType = List.of(1, 2, 3, 4, 5);
System.out.println("Same Type: " + validateSameType(sameType));
List<Object> differentType = List.of(1, "hello", 3.14);
System.out.println("Different Type: " + validateSameType(differentType));
List<Double> positiveNumbers = List.of(1.0, 2.5, 3.0
Add your comment